[JetpackCompose/Android] DAO object doesn’t update and how to solve this

Jetpack Compose

Tech stack

  • Jetpack Compose
  • Room⭐️ //related this article
  • Daggar hilt

In my case, I had to update the room object through dao. The following figure is this case of data flow.

Application

It is something like a journal application. Users write journal and save. Of cource they can edit delete.

View -- object --> ViewModel -- object --> Repository -- object --> Room

But when editting journal won't save.

Cause

In Room, we can find a entity by using query even you define as a method like below.

JournalDao.kt

@Dao
interface JournalDAO {

    @Insert
    suspend fun insertJournal(journal: Journal)

    @Update
    suspend fun updateJournal(journal: Journal)

    @Delete
    suspend fun deleteNote(journal: Journal)

    @Query("SELECT * FROM journal_table WHERE id= :id")
    fun getJournal(id: Int): Flow<Journal>

    @Query("SELECT * FROM journal_table")
    fun getAllJournals(): Flow<List<Journal>>
}

When I was tring to update a journal I didn't realize that it had to have primary key. So I was trying to do it without primary key. That's why I couldn't update it. It was need to set primary key to Room object.

    fun onSave(journal: Journal, completion: VoidCallback? = null) {
        viewModelScope.launch {
            val result = repository.getJournalStream(journal.id).firstOrNull() // Get the target jounal which will be updated.
            Log.d(TAG, "Result of getJournalStream(): $result")
            if (result == null) {
                repository.insertJournal(journal)
            } else {
                // Update could not work unless pk match as journal.
                try {
                    val journalWithPk = journal.copy(primKey = result.primKey) // set primary key to new journal.
                    Log.d(TAG, "Add pk to journal: $journalWithPk")
                    repository.updateJournal(journalWithPk)
                } catch (e: Exception){
                    // No error happens.
                    Log.d(TAG, e.toString())
                }
            }
            val dummy = repository.getAllJournalStream().first()
            Log.d(TAG, "Result of getAllJournalStream(): $dummy")
            completion?.invoke()
        }
    }

コメント

タイトルとURLをコピーしました