Skip to content
Advertisement

Dao Room database. How to SUM all the amounts and view it as a TextView?

I am creating a simple expence tracker. I can add items to the database and view them in a recyclerview. But when I try to SUM all values from a column, it only return 0 instead of the sum of all the values. First of all, here’s the column which values I am trying to sum together.

JavaScript

And here is the Dao Query:

JavaScript

Item is the name of my Entity class

I am using AsyncTask like this:

JavaScript

And in my Main View Model I create the method

JavaScript

Which I then call in my Activity class.

I am calling this method in onCreate like this:

JavaScript

I have logged the value of tempSum, and it is 0 when onCreate is being called.

Does anyone know what could be the problem? Is there anything wrong with my dao Query?


EDIT 1:

I changed it so I access getTotalSum directly, instead of using Async. In my Activity, I then observe the value like this:

JavaScript

But it tells me: Attempt to invoke virtual method ‘int java.lang.Integer.intValue()’ on a null object reference. I do not get how sumAllItems is null?


EDIT 2.

Full Error output from the error on EDIT1

JavaScript

EDIT 3 – SOLUTION

With the help from Stephane Piedjou, the solution was to create an observer. The problem in Edit 1 was that I did not observe the data directly from dao.

I changed this and it worked.

JavaScript

Advertisement

Answer

Your query is run asynchronously. task.execute() will run the operation on another thread and when you assign the sumValue (task.sumValue) it is still null as the other thread has not completed its operation. A solution is in your dao instead of returning int your return a live data

public LiveData<Integer> getTotalSum();

In your repository instead of calling AsyncTask you call the getTotaSum() directly

JavaScript

And you can observe for the result in your activity with something similar to this.

JavaScript

For more info about live data see here

Advertisement