【问题标题】:How to populate a fragment with an entity from a Room Database?如何使用房间数据库中的实体填充片段?
【发布时间】:2021-03-13 22:01:54
【问题描述】:

在导航到片段时,我正在传递 Room DB 实体的 ID。我现在正在尝试将 textview 的文本设置为该实体的属性。

这是我目前正在尝试的,但它似乎不起作用:

我的 Fragment 中有一个名为 editPlanViewModel 的 ViewModel。这是 ViewModel:

class EditPlanViewModel(
private val trainingPlanKey: Long = 0L,
val database: TrainingPlannerDatabaseDao) : ViewModel() {

private val viewModelJob = Job()
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)

private val _plan = MutableLiveData<TrainingPlan>()
val plan: LiveData<TrainingPlan>
    get() = _plan

init {
    uiScope.launch {
        withContext(Dispatchers.IO) {
            Log.d("DEBUG", "Before get")
            _plan.value = database.get(trainingPlanKey) ?: return@withContext
            Log.d("DEBUG", "After get")
        }
    }
}

override fun onCleared() {
    super.onCleared()
    viewModelJob.cancel()
}

在 TrainingPlannerDatabaseDao 中:

@Query("SELECT * FROM training_plan_table WHERE planId = :key")
fun get(key: Long): TrainingPlan?

LiveData 计划应该改变,所以我在 Fragment 中设置了一个观察者:

editPlanViewModel.plan.observe(viewLifecycleOwner, { plan ->
    Log.d("DEBUG", "In observer")
    if (plan != null) {
        binding.planName.text = plan.name
    }
})

似乎永远不会触发观察者。我添加了三个日志,但只触发了“Before get”。

有谁知道为什么观察者没有被触发或有其他方法可以达到相同的结果?

【问题讨论】:

    标签: android kotlin android-room android-mvvm


    【解决方案1】:

    如果你没有超过这条线,没有例外:

    _plan.value = database.get(trainingPlanKey) ?: return@withContext
    

    那么它只能是database.get(trainingPlanKey) 为空并且一切都按预期工作。

    【讨论】:

    • 我确实错误地传递了我的密钥,所以我的查询返回 null。为什么查询失败时查询下面没有代码运行?
    • 由于您添加了?: return,这实质上意味着如果左侧是null,则返回! kotlinlang.org/docs/null-safety.html#elvis-operator
    猜你喜欢
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多