1

I want to get the integer value from my Expense table which is a sum of the expenses(amount column) total expense.

In my Expense Entity class

//This is the column Amount which I want the sum of all values in this column and get single integer value total amount
@ColumnInfo(name = "Amount")
private int amount;

public int getAmount() {
    return amount;
}

In my Dao class here is the function which give me total amount through LiveData

@Query("SELECT SUM(Amount) from Expense_table")
LiveData<Integer> getTotalExpenseAmount();

This is from Repository class

public LiveData<Integer> getTotalExpenseAmount() {
    return expenseDao.getTotalExpenseAmount();
}

And this is from ViewModel class

public LiveData<Integer> getTotalExpenseAmount() {
    return expenseRepository.getTotalExpenseAmount();
}

Everything works fine as it should be. But in my case I don't want to get this through liveData observer, instead I want to get this total amount value itself. Where I don't have to use the observer again and again

expenseViewModel.getTotalExpenseAmount().observe(MainActivity.this, new Observer<Integer>() {
    @Override
    public void onChanged(Integer integer) {
        totalExpense = integer;

        addDataSet();
        Toast.makeText(MainActivity.this, "Total Expense " + totalExpense, Toast.LENGTH_SHORT).show();
    }
});

I've to get this total amount value in many classes where I don't want to observe this again and again. Please tell me any shortcut to do this efficiently. I'll be very thankful to you guys if you solve my problem

guipivoto
  • 18,327
  • 9
  • 60
  • 75
Nabeel Ahmed
  • 223
  • 5
  • 15
  • 1
    I think you can replace "LiveData getTotalExpenseAmount();" by "Integer getTotalExpenseAmount();" – guipivoto Oct 16 '19 at 18:04
  • 1
    I did the same as you told me to do, but it gives me this error. Error : "Cannot access database on the main thread since it may potentially lock the UI for a long period of time." – Nabeel Ahmed Oct 17 '19 at 04:25
  • can you show me how to make getTotalExpenseAmount() method an AnsyncTask as I have some other methods like this 'private static class InsertIncomeAsyncTask extends AsyncTask – Nabeel Ahmed Oct 17 '19 at 04:32
  • Please take a look at my this question also... https://stackoverflow.com/questions/58425494/how-can-i-create-asynctask-of-my-gettotalincomeamount-which-is-an-integer-type – Nabeel Ahmed Oct 17 '19 at 06:45

0 Answers0