简体   繁体   中英

Can't Update Room database item

I'm trying to update a column of an item in a room database but the item isn't updating.

My Entity:

    @Entity(tableName = "order_summary_table")
    data class SummaryItem(
    @ColumnInfo(name = "quantity")
    var quantity: Int = -1,

    @ColumnInfo(name = "item_name")
    val name: String,

    @ColumnInfo(name = "item_price")
    var price: Int
    ) {
    @PrimaryKey(autoGenerate = true)
    var itemId: Long = 0
    }

Here is my Dao:

    @Update
    fun update(summaryItem: SummaryItem)

    @Query("SELECT * FROM order_summary_table WHERE itemId = :key")
    suspend fun get(key: Long): SummaryItem?

Function in the ViewModel. I'm using Kotlin Coroutines for database operations. My database has 3 columns: quantity, name and price. Here I wrote a function to update the quantity column of an item in the database:

   fun saveEditedItem(quantity: Int, summaryItemKey: Long) {
      coroutineScope.launch {
           val item = database.get(summaryItemKey)
           val editedItem = SummaryItem(quantity, item!!.name, item.price)
           updateSummaryItem(editedItem)
       }
   }

   private suspend fun updateSummaryItem(summaryItem: SummaryItem) {
      withContext(Dispatchers.IO) {
          database.update(summaryItem)
      }
   }

Fragment.kt file, Here I set an OnClickListener to update the item on button click but the item isn't getting updated.

   val quantityText = binding.editQuantityText
   binding.saveButton.setOnClickListener {
        val editTextValue = quantityText.text
        val quantity = Integer.parseInt(editTextValue.toString())
        viewModel.saveEditedItem(quantity, arguments.summaryItemKey)
   }

i think there is 2 ways.

1.in saveEditedItem(...) fun add itemId PrimaryKey

coroutineScope.launch {
    val item = database.get(summaryItemKey)
    val editedItem = SummaryItem(quantity, item!!.name, item.price)
    editedItem.itemId = item.itemId
    updateSummaryItem(editedItem)
}

2.update item itself.

coroutineScope.launch {
        val item = database.get(summaryItemKey)
        item.quantity = //newQuantity
        item.name = // newName
        item.price = // newPrice
        updateSummaryItem(item)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM