【问题标题】:room not returning results for livedata房间没有返回 livedata 的结果
【发布时间】:2021-01-23 14:46:41
【问题描述】:

我正在尝试从 Android Room 返回 LiveData。我无法将结果作为 LiveData 返回。

这是道的节选

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

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

getAllTransactions() 调用无异常运行,但不返回结果。另一方面,getMyTransactions() 返回选择查询结果。

在视图模型中:myLiveData = repository. getAllTransactions()

活动中:

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

怎么了?

【问题讨论】:

  • 请提供如何处理这些数据的代码(viewmodel、UI),这还不够
  • 更新了问题
  • @AskQ 检查答案,看看它是否能解决您的问题

标签: android android-room android-livedata


【解决方案1】:

问题是这个myLiveData = repository. getAllTransactions() 部分是在您创建视图模型实例时完成的。

在您开始观察myLiveData之前,查询结果已经发布。

你应该做的是在ViewModel中做一个方法

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

在活动中,

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

【讨论】:

  • 我需要调用 removeObservers 吗?像 val localdata = githubListViewModel?.loadLocalData() localdata?.removeObservers(this) 之前观察?
  • 底层数据结构管理它,它不会保持重复。
【解决方案2】:

我认为问题出在myLiveData = repository.getAllTransactions()。

由于getAllTransactions() 返回LiveData,将repository.getAllTransactions 分配给成员变量类似于在其上注册观察者,并且观察者(在您的情况下为myLiveData)不会被触发或通知,除非有底层数据库的变化。

试试下面的,

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

【讨论】:

    猜你喜欢
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    相关资源
    最近更新 更多