0

I am using Kotlin and Room for some basic operations. All the operations work fine but the updateAll, it didn't update the database. The Dao like below:

@Dao
interface ItemListDao {

    @Insert
    fun insertAll(itemLists: List<ItemList>)

    @Insert//(onConflict = OnConflictStrategy.IGNORE)
    fun insert(itemLists: ItemList)

    @Delete
    fun delete(itemList: ItemList)

    @Update(onConflict = OnConflictStrategy.REPLACE)
    fun update(itemList: ItemList)

    @Transaction
    fun upset(itemList: ItemList) {
        try {
            insert(itemList)
        } catch (exception: SQLiteConstraintException) {
            update(itemList)
        }
    }

    @Transaction
    fun updateAll(itemLists: List< ItemList>) {
        itemLists.forEach {
            upset(it)
        }
    }

}

@Entity
data class ItemList constructor(
    @PrimaryKey val listId: String,
    val displayName: String
}

The updateAll function is used to check when the element in the list of itemLists existed, then update the element, if not then insert.

Also I think should I query to check if the itemList exist if not insert, if yes then update?

Not sure which one is better too.

EDIT: I used

@Update(onConflict = OnConflictStrategy.REPLACE)

on the udpate method, and then in updateAll, I call update only, but actually can't pass the unit test.

EDIT My currect approach

@Transaction
    fun updateAll(itemLists: List< ItemList>) {
     itemLists.forEach {
        val itemList = findItemList(it.listId)
        if (itemList != null) {
            update(it)
        } else {
            insert(it)
        }
       update(it)
    }
   }

Any help? Thanks a lot!

William Hu
  • 15,423
  • 11
  • 100
  • 121
  • check this answer https://stackoverflow.com/a/54260385/5760831. You can directly update if not exist insert, by adding onConflictStrategy. – Xuzan Nov 29 '19 at 04:54
  • @Xuzan thanks, If you see the code above `update` has the ```@Update(onConflict = OnConflictStrategy.REPLACE)``` and my `updateAll` just call udpate, but it doesn't work as expected. – William Hu Nov 29 '19 at 06:23
  • @WilliamHu can you paste your ItemList entity? – Shripad Jadhav Nov 29 '19 at 07:38
  • After I uninstall the app then` @Update(onConflict = OnConflictStrategy.REPLACE)` works. – William Hu Nov 29 '19 at 08:22

0 Answers0