Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 通过使用ROOM数据库,如何在不使用LiveData或不观察LiveData的情况下从表中获取值?_Android_Android Room_Android Livedata - Fatal编程技术网

Android 通过使用ROOM数据库,如何在不使用LiveData或不观察LiveData的情况下从表中获取值?

Android 通过使用ROOM数据库,如何在不使用LiveData或不观察LiveData的情况下从表中获取值?,android,android-room,android-livedata,Android,Android Room,Android Livedata,我想从我的费用表中获取整数值,它是费用(金额列)总费用的总和 在我的课程中 //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

我想从我的费用表中获取整数值,它是费用(金额列)总费用的总和

在我的课程中

//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;
}
在我的Dao类中,这里有一个函数,它通过LiveData为我提供总量

@Query("SELECT SUM(Amount) from Expense_table")
LiveData<Integer> getTotalExpenseAmount();
@Query(“从费用表中选择金额”)
LiveData getTotalExpenseAmount();
这来自存储库类

public LiveData<Integer> getTotalExpenseAmount() {
    return expenseDao.getTotalExpenseAmount();
}
public LiveData getTotalExpenseAmount(){
return expenseDao.getTotalExpenseAmount();
}
这是来自ViewModel类

public LiveData<Integer> getTotalExpenseAmount() {
    return expenseRepository.getTotalExpenseAmount();
}
public LiveData getTotalExpenseAmount(){
return expenseRepository.getTotalExpenseSeamount();
}
一切正常。但在我的例子中,我不想通过liveData observer获得这个值,相反,我想获得这个总量值本身。在那里我不必一次又一次地使用观察者

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();
    }
});
expenseViewModel.getTotalExpenseAmount().observe(MainActivity.this,new Observer()){
@凌驾
更改后的公共void(整数){
总费用=整数;
addDataSet();
Toast.makeText(MainActivity.this,“总费用”+总费用,Toast.LENGTH_SHORT).show();
}
});
我必须在很多类中得到这个总量值,我不想一次又一次地观察它。请告诉我有什么捷径可以有效地做到这一点。
如果你们能解决我的问题,我会非常感谢你们的。

我想你们可以用“Integer getTotalExpenseAmount();”替换“LiveData getTotalExpenseAmount();”;“我做了和你们说的一样的事情,但它给了我这个错误。错误:“无法访问主线程上的数据库,因为它可能会长时间锁定UI。”您能告诉我如何将getTotalExpenseAmount()方法设置为AnsyncTask,因为我还有一些其他方法,如‘私有静态类InsertInCoamesyncTask Extendes AsyncTask’请查看我的此问题。。。