我如何在房间数据库Android中求和 [英] How can i sum value in room database android
问题描述
我想知道如何对房间数据库中的值求和.
I want to know that how can i sum value in the room database .
假设我已将此值(10,000)插入到会议室数据库中,并且我想向数据库(20,000)中插入新值,并且我希望新值与旧值相加而不替换它.
Let say i have insert this value (10,000) in the room database and i want to insert new value to database (20,000) and i want the new value to be sum with old value not replace it .
我该怎么做??
代码示例:
数据库表:
@entity
class sum (
id : int ,
value : Long )
Dao :
@insert (onConflict = OnConflictStrategy.REPLACE)
suspend fun insert (model :sum)
what shoud i use instead of above insert .
@Query("SELECT * FROM sum")
fun getall () : LiveData<sum>
和活动中:
late init var : viewmodel : Viewmodeldatabase
val textvalue : TextView
viewmodel = Viewmodelprovider(this).get(Viewmodeldatabase::class.java)
textvalue = findvidwbyid(R.id.text)
viewmodel.insert(sum(1 , 10000)
// when the above value insert , if there is an old value sum with it and not replace it or remove it
viewmodel.getall.observe(this , Observer {
textvalue.text = it.value
)}
谢谢大家观看我的代码并为我提供帮助.
thank's guys for watch my code and help me .
推荐答案
尝试在dao中添加下一个方法:
Try to add next method in your dao:
@Query("UPDATE sum SET value = value + :addValue WHERE id =:id")
suspend fun updateSum(id: Int, addValue: Long)
然后您可以从ViewModel/Activity中调用它
Then you can call it from your ViewModel/Activity
更新
对于用于更新/插入的单个方法,请将这些方法放在dao中:
For single method for update/insert put these methods in dao:
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertSum(model: Sum)
@Query("UPDATE sum SET value = value + :value WHERE id = :id")
suspend fun updateSum(id: Int, value: Long)
@Query("SELECT * FROM sum WHERE id = :id")
suspend fun getSumById(id: Int): Sum?
@Transaction
suspend fun updateOrInsertSum(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)
}
当然,您还应该将方法updateOrInsertSum
添加到存储库和viewmodel中
然后,如果您首次要求id ='1',则会插入值:
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
这篇关于我如何在房间数据库Android中求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!