我正在尝试从Android Room返回LiveData。我无法将结果作为LiveData返回。
以下是Dao
的摘录
@Query("SELECT * FROM transaction_table")
LiveData<List<MyTransaction>> getAllTransactions();
@Query("SElECT * FROM transaction_table")
List<MyTransaction> getMyTransaction();
getAllTransactions()
调用无例外运行,但是不返回结果。另一方面,getMyTransactions()
返回选择查询结果。
SDK Version: 23
Room Version: 2.1.0-beta01
编辑:
我正在初始化时填充数据库以进行测试。这是代码
private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> {
private static final String TAG = "PopulateDbAsync";
private final TransactionDao mDao;
PopulateDbAsync(TransactionDatabase db) {
mDao = db.transactionDao();
}
@Override
protected Void doInBackground(Void... voids) {
mDao.deleteAll();
MyTransaction transaction = new MyTransaction();
transaction.setCardNumber("0123023403450456");
long result = mDao.insert(transaction);
Log.d(TAG, "doInBackground: " + String.format(Locale.US, "Result %d", result));
transaction = new MyTransaction();
transaction.setCardNumber("0123023403450457");
result = mDao.insert(transaction);
Log.d(TAG, "doInBackground: " + String.format(Locale.US, "Result %d", result));
LiveData<List<MyTransaction>> currentTransactions = mDao.getAllTransactions();
List<MyTransaction> txns = currentTransactions.getValue();
List<MyTransaction> transactions = mDao.getMyTransaction();
if(transactions != null) {
Log.d(TAG, "doInBackground: " + String.format(Locale.US, "Size = %d", transactions.size()));
}
return null;
}
}
答案 0 :(得分:0)
如果不观察LiveData,就无法检索它。这就是以下代码根本不起作用的原因。
LiveData<List<MyTransaction>> currentTransactions = mDao.getAllTransactions();
要使其正常工作,请先观察LiveData,然后侦听数据更改:
mDao.getAllTransactions().observe(this, new Observer<List<MyTransaction>>() {
@Override
public void onChanged(List<MyTransaction> myTransactionList) {
}
});