Search code examples
androidandroid-roomandroid-lifecycle

Android Room query not returning the LiveData


I am trying to return LiveData from Android Room. I am having trouble returning the result as LiveData.

Here is the excerpt from Dao

  @Query("SELECT * FROM transaction_table")
  LiveData<List<MyTransaction>> getAllTransactions();

  @Query("SElECT * FROM transaction_table")
  List<MyTransaction> getMyTransaction();

The getAllTransactions() call runs without an exception but, does not return the results. On the other hand, getMyTransactions() returns select query results.

SDK Version: 23
Room Version: 2.1.0-beta01

Edit:

I am populating the database on initialization for testing. Here is the code

  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;
      }
  }

Solution

  • LiveData can't be retrieved without observing it. That's why the following code didn't work at all.

    LiveData<List<MyTransaction>> currentTransactions = mDao.getAllTransactions();
    

    To make it work observe the LiveData first then listen for the data changes:

     mDao.getAllTransactions().observe(this, new Observer<List<MyTransaction>>() {
                @Override
                public void onChanged(List<MyTransaction> myTransactionList) {
    
                }
            });