How Can I Sum Value In Room Database Android
I want to know that how can i sum value in the room database . Let say i have insert this value (10,000) in the room database and i want to insert new value to database (20,000) an
Solution 1:
Try to add next method in your dao:
@Query("UPDATE sum SET value = value + :addValue WHERE id =:id")suspendfunupdateSum(id: Int, addValue: Long)
Then you can call it from your ViewModel/Activity
UPDATE
For single method for update/insert put these methods in dao:
@Insert(onConflict = OnConflictStrategy.REPLACE)suspendfuninsertSum(model: Sum)@Query("UPDATE sum SET value = value + :value WHERE id = :id")suspendfunupdateSum(id: Int, value: Long)@Query("SELECT * FROM sum WHERE id = :id")suspendfungetSumById(id: Int): Sum?
@TransactionsuspendfunupdateOrInsertSum(sum: Sum) { // <-- this method updates value or insert new item, if id is not found
getSumById(sum.id)?.let { updateSum(sum.id, sum.value) } ?: insertSum(sum)
}
Of course you should add method updateOrInsertSum
to your repository and viewmodel as well
Then if you call for id = '1' for the first time value will be inserted:
viewmodel.updateOrInsertSum(Sum(1 ,10000)) // <-- id = 1, value = 10000
On the next call item will be updated with the same method:
viewmodel.updateOrInsertSum(Sum(1 ,20000)) // <-- id = 1, value = 10000+2000
Solution 2:
In your Dao, I see that you use the function getAll(), lets say that you save them into a list of integers
val list: List<Int>//list holding all of you data returned in the onChanged method of the observer callback(or the lambda callback in case of Kotlin)
lets say that you want to update the value at position 1:
@Updatepublicvoidupdate(newVal: Int);
and when calling the update function pass to it the summation of the old value coming from the "list" I mentioned earlier and the newValue
database.dao.update(list[1] + newValue)
Post a Comment for "How Can I Sum Value In Room Database Android"