如何使用房间数据库中的实体填充片段?

How to populate a fragment with an entity from a Room Database?

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

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

我的 Fragment 中有一个名为 editPlanViewModel 的 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”。

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

如果您没有例外地越过这条线:

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

那么只能是 database.get(trainingPlanKey) 为空,一切正常。