https://kotlinlang.org logo
Title
a

Arslan Mushtaq

02/23/2020, 7:21 PM
I have a cart which stores data in Room Database. How is it possible for me to automatically update my Grand Total when an item Sub Total is changed within the Cart? I’m using the following SQLite functions:
@Query("SELECT * FROM cart_table")
fun getAllItemsFromCart(): LiveData<List<Cart>>

@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(cart: Cart)

@Query("DELETE FROM cart_table")
suspend fun deleteAllItemsFromCart()

@Delete
suspend fun deleteItemFromCart(cart: Cart)

@Query("SELECT COUNT(*) FROM cart_table")
suspend fun itemCount(): Int

@Query("SELECT SUM(total) FROM cart_table")
fun getGrandTotal(): LiveData<Double>

@Query("UPDATE cart_table SET quantity = quantity + 1 WHERE id = :id")
suspend fun increaseQuantity(id: Int)

@Query("UPDATE cart_table SET quantity = quantity - 1 WHERE id = :id")
suspend fun decreaseQuantity(id: Int)
a

Ahmed Ibrahim

02/23/2020, 7:30 PM
I think you've already achieved that in this method
@Query("SELECT SUM(total) FROM cart_table")
fun getGrandTotal(): LiveData<Double>
Once the cart_table gets updated the LiveData will emit a new grand total.
a

Arslan Mushtaq

02/23/2020, 7:33 PM
But it isn’t being called when I update the quantity from my RecyclerView Adapter
a

Ahmed Ibrahim

02/23/2020, 7:39 PM
Your Dao looks fine to me, so I'd advice you to put break points inside the Dao's generated code and see if they behave correctly.
a

Arslan Mushtaq

02/23/2020, 7:41 PM
Yes, they work fine. Initially when I call
getGrandTotal()
in my Fragment. It works but when I try to call it from my adapter. It’s not updating the result.
a

Ahmed Ibrahim

02/23/2020, 7:42 PM
How are your listening to the livedata inside the adapter?
a

Arslan Mushtaq

02/24/2020, 1:01 AM
Solved it using the @Update Annotation.