Search code examples
androidkotlinandroid-room

Updating a Single Column In Room Database


That's the function I'm using for update:

private fun updateSettingsDatabase(settingsDao: SettingsDao) {
        lifecycleScope.launch {
            settingsDao.update(SettingsEntity(
                1,
                nightMode=nightModeResult,
            ))
        }
}

@Query("SELECT * FROM `settings-table`")
fun fetchCurrentSettings(): Flow<List<SettingsEntity>>

I specified nightMode= because I thought that this way I'm only updating this column, but it turns out that it resets every column, how do I update a single column, while keeping the values the rest of the columns?


Solution

  • If it is single or few columns that you want to update then you can write custom query.

    In your dao class

    @Query("UPDATE settings-table SET nightMode = :nightModeResult WHERE id = :id")
    fun updateNightMode(id: Int, nightModeResult: Any): Int