Raju Ugale
Raju Ugale

Reputation: 4291

room not returning results for 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.

in viewmodel: myLiveData = repository. getAllTransactions()

in activity:

 mViewModel!!.myLiveData.observe(this, Observer<List< MyTransaction >> { repositories: List< MyTransaction > ->
})

whats wrong?

Upvotes: 0

Views: 536

Answers (2)

Dhanuesh
Dhanuesh

Reputation: 1596

I believe the issue is with myLiveData = repository.getAllTransactions().

Since getAllTransactions() returns a LiveData, assigning repository.getAllTransactions to a member variable is similar to registering an observer on it and the observer, in your case myLiveData, won't be triggered or notified unless there's a change in the underlying database.

Try the following,

// in viewmodel
fun myLiveData() = repository.getAllTransactions()

//try to log in the activity and you will see the data
Log.i("activity",mViewModel.myLiveData().value.toString())

//since myLiveData function returns a livedata, you can register observers on to it as well
mViewModel!!.myLiveData().observe(this, Observer<List< MyTransaction >> { repositories: List< MyTransaction > ->
})

Upvotes: 0

rahat
rahat

Reputation: 2056

The problem is that this myLiveData = repository. getAllTransactions() part is done When you create instance of viewmodel.

Before you start to observe myLiveData the query result has been posted.

What you should do is to make a method in ViewModel

fun getAllTransactions():LiveData<List<MyTransaction>> {
  return repository. getAllTransactions();
}

And in the activity,

mViewModel!!.getAllTransactions().observe(this, Observer<List< MyTransaction >> { repositories: List< MyTransaction > ->
//your code goes here
})

Upvotes: 1

Related Questions