android - 使用 ViewModel 构造函数而不是 ViewModelProvider 能够根据参数从 Room 数据库中获取数据

标签 android viewmodel android-room android-livedata

当基于此 codelab 使用带有 ViewModel 和 LiveDate 的 Room 数据库时为了使用带参数的查询,我没有找到任何解决方案,所以我尝试为 View 模型类和存储库类创建另一个构造函数,但我注意到在 CodeLab 他们根本不使用 View 模型构造函数相反,他们使用 View 模型提供程序,所以我对其进行了更改并使用了new StoryViewModel(getApplication(),"Fiction");代替new ViewModelProvider(this).get(StoryViewModel.class);
我不知道这是否有什么问题。它现在工作正常,但如果是这样 为什么我们不总是使用它? 为什么我们要使用 View 模型提供者?

如果我做错了,那么如何根据参数从数据库中检索数据?

谢谢你。

最佳答案

您不应该直接使用 viewModel 构造函数,因为系统会创建 viewModel 或从缓存中获取它。如果你想将参数传递给 viewModel 构造函数,你应该使用这样的 viewModel 工厂:

class ViewModelFactory(params) : ViewModelProviders.Factory {

     override fun <T : ViewModel> create(modelClass: Class<T>): T {
          return modelClass.getConstructor(params::class.java).newInstance(params);
     }

}

...

override fun onCreate(...) {

  viewModel = ViewModelProviders.of(this, ViewModelFactory(params)).get(MyViewModel::class.java)s
}

关于android - 使用 ViewModel 构造函数而不是 ViewModelProvider 能够根据参数从 Room 数据库中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59693507/

相关文章:

c# - C# 中的 Moq Application.Current.MainWindow

android - View 不会与数据绑定(bind)

android - 单个 ViewModel 中的多个 LiveData 对象

Android自定义复合 View 保存和恢复状态不起作用

asp.net-mvc - asp mvc 使用 View 模型在 View 中列出产品详细信息

Android Room 无法弄清楚如何将此字段保存到数据库中

android - 从 Room DB 获取单个项目。从 View 模型调用函数

Android - 旋转图像避免 OutOfMemory

android - 将数据从 DialogFragment 发送到 Fragment

android - 将 map globe Rajawali 实现到 fragment Android