Initializing ViewModel in fragment Android java

回眸只為那壹抹淺笑 提交于 2020-06-17 09:17:16

问题


I am trying to initialize my viewmodel object in the FirstFragment.java file of BasicActivity. All theses four codes are failed. The documentation could not help me much.

mViewModel = new ViewModelProvider(this).get(MyViewModel.class);
mViewModel = new ViewModelProvider(requireActivity()).get(MyViewModel.class);
mViewModel = new ViewModelProvider(getActivity()).get(MyViewModel.class);
mViewModel = new ViewModelProvider(FirstFragment.class).get(MyViewModel.class);

On the other hand, public ViewModelProvider(@NonNull ViewModelStoreOwner owner) ViewModelProvider is taking ViewModelStoreOwner as its parameter and in the FragmentActivity.java ViewModelStore getViewModelStore() method of ViewModelStore interface is implemented may be in a factory pattern.

@NonNull
        @Override
        public ViewModelStore getViewModelStore() {
            return FragmentActivity.this.getViewModelStore();
        }

Help me initializing ViewModel


回答1:


Initializing your viewModel goes like:

if you are using

implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'

and Intialize your viewModel

viewModel = ViewModelProviders.of(this,viewModelFactory).get(MyViewModel.class);

but it's deprecated now. So update the dependency to:

implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'

and initial your viewModel as follow:

viewModel = new ViewModelProvider(this,viewModelFactory).get(MyViewModel.class);

viewModelFactory is optional.



来源:https://stackoverflow.com/questions/61395560/initializing-viewmodel-in-fragment-android-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!