去年夏天,我开始使用 Android 的架构组件(Room、ViewModel、LiveData)重构我的 Android 应用程序。
我有两个 Room 存储库,其中一个由应用程序的多个视图(片段)访问。因此,我使用了AndroidViewModel,它可以访问此存储库并在我的MainActivity.
new ViewModelProvider(this).get(CanteensViewModel.class);
Run Code Online (Sandbox Code Playgroud)
在我的两个片段中,我通过
new ViewModelProvider(getActivity()).get(CanteensViewModel.class);
Run Code Online (Sandbox Code Playgroud)
直到昨天,这一切都完美无缺。但是后来我更新了我的依赖项,从androidx.lifecycle2.2.0 版开始这不再起作用了。我总是得到一个例外(siehe EDIT 2):
Caused by: java.lang.InstantiationException: java.lang.Class<com.(...).CanteensViewModel> has no zero argument constructor
Run Code Online (Sandbox Code Playgroud)
所以我检查了文档,正如我理解的那样,我现在应该/可以使用
ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication()).create(CanteensViewModel.class);
Run Code Online (Sandbox Code Playgroud)
获取我的 ViewModel。但是使用这种方法我无法添加owner( ViewModelProviders 构造函数的参数),这导致了问题,即我无法从片段内部真正访问我在 Activity 中创建的 ViewModel。
有没有办法可以从片段内部访问 Activity 的 ViewModel?或者最好通过以下方式在每个片段中重新创建ViewModel
ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication()).create(CanteensViewModel.class);
Run Code Online (Sandbox Code Playgroud)
而不是在活动中创建它?
编辑:
当我使用 的另一个构造函数时ViewModelProvider,它似乎有效,其中 aAndroidViewModelFactory是第二个参数。
new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(CanteensViewModel.class);
Run Code Online (Sandbox Code Playgroud)
在我的MainActivity我可以访问CanteensViewModel我的Fragment通过
new ViewModelProvider(requireActivity()).get(CanteensViewModel.class);
Run Code Online (Sandbox Code Playgroud)
针对上述异常编辑 2 Stacktrace: …