user18145931
user18145931

Reputation:

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?

Upvotes: 3

Views: 5077

Answers (2)

Kamal
Kamal

Reputation: 355

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

Upvotes: 5

rasfarrf5
rasfarrf5

Reputation: 237

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

Upvotes: 1

Related Questions