'Updating a Single Column In Room Database

That's the function I'm using for updat

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 colummn, 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 1:[1]

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

Solution 2:[2]

Instead of creating new SettingsEntity object. Try to get the exact object first then update the value into it and finally update to Dao.

For Eg.,

@Query("SELECT * FROM `settings-table` where id=:id")
fun getSettingEntityById(id: Int): Flow<SettingsEntity>

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun update(entity: SettingsEntity)


private fun updateSettingsDatabase(settingsDao: SettingsDao) {
    val entity = settingsDao.getSettingEntityById(1) // Replace 1 with exact id
    entity.updateValue(newValue)

    lifecycleScope.launch {
        settingsDao.update(entity)
    }
}

Hope this helps :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kamal
Solution 2 rasfarrf5