Cannot resolve ViewModelProvider construction in a fragment?

后端 未结 4 1818
悲哀的现实
悲哀的现实 2021-02-19 05:28

I have been spending a lot of time trying to figure out why in the code below (towards the end), I get an error on ViewModelProvider(this). I also tried getActivity() instead of

4条回答
  •  名媛妹妹
    2021-02-19 05:48

    Firstly you need to use the latest version of lifecycle extension. It should be:

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

    or any updated version.

    Then you should use requireActivity() instead of getActivity(). This way you will ensure that the activity is attached an not getting a NullPointerException.

    ItemSetupFragmentModel model = new ViewModelProvider(requireActivity()).get(ItemSetupFragmentModel.class);
    

    Note: ViewModel Overview and Declaring Dependencies

    I had to restart cache after adding the library to the Gradle file. There is no need to use requireActivity(), this is enough.

提交回复
热议问题