How can i sum value in room database android

Viewed 781

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) and i want the new value to be sum with old value not replace it .

how can i do that .?

example of code :

Database Table :

@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>

and in activity :

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 .

2 Answers

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)

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)
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)
}

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 

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:

@Update
public void update(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)
Related