Home > OS >  Updating a Single Column In Room Database
Updating a Single Column In Room Database

Time:05-07

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?

CodePudding user response:

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 :)

CodePudding user response:

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
  • Related