Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

android - 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?

question from:https://stackoverflow.com/questions/65860525/room-not-returning-results-for-livedata

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...