I want to get total income amount from my Income table which have Amount table
@ColumnInfo(name = "Amount")
private int amount;
And in my IncomeDao I've
@Query("SELECT SUM(amount) from income_table")
Integer getTotalIncomeAmount();
And in my IncomeRepository I've
public Integer getTotalIncomeAmount()
{
return incomeDao.getTotalIncomeAmount();
}
In my IncomeViewModel
public Integer getTotalIncomeAmount()
{
return incomeRepository.getTotalIncomeAmount();
}
And I call this in my Main thread like this
totalIncome = incomeViewModel.getTotalIncomeAmount();
But it gives me the error that 'Cannot access database on the main thread since it may potentially lock the UI for a long period of time.'
I know this error can be remove by creating LiveData<Integer> getTotalIncomeAmount()
.
But I don't want to do this by LiveData
because I've to observe it which is not good in my case.
I want someone to show me how to create AsyncTask
of this method in my IncomeRepository
class because I know this is the only way to get rid of this error.
I'm fairly new in programming.
As I created other AsyncTask
like this in my IncomeRepository
private static class UpdateIncomeAsyncTask extends AsyncTask<Income, Void, Void>
{
private IncomeDao incomeDao;
private UpdateIncomeAsyncTask(IncomeDao incomeDao)
{
this.incomeDao = incomeDao;
}
@Override
protected Void doInBackground(Income... incomes)
{
incomeDao.update(incomes[0]);
return null;
}
}
I just need someone to complete private static class TotalIncomeAmountAsyncTask extends AsyncTask<Void, Void, Void>
for me. I tried very hard but I could succeed.
Thanks in advance