Cannot create an instance of class ViewModel

后端 未结 23 2654
[愿得一人]
[愿得一人] 2020-12-05 12:37

I am trying to write a sample app using Android architecture components and but even after trying for days I could not get it to work. It gives me the above exception.

23条回答
  •  -上瘾入骨i
    2020-12-05 12:57

    I had this problem following google's roomdb CodeLab. Solution was changing the following.

    Edited

    Add the following Build dependencies to Gradle file (as of 2/22/2020)

    implementation 'androidx.fragment:fragment:1.2.2'
    implementation 'androidx.lifecycle:lifecycle-process:2.2.0'
    implementation 'androidx.lifecycle:lifecycle-service:2.2.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.2.0'
    annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.2.0'
    

    Imports within the fragment

    import androidx.lifecycle.ViewModelProvider;
    import androidx.fragment.app.Fragment;
    import androidx.lifecycle.Observer;
    

    Creating the viewModel. Add one of the following methods.

    Note: I'v seen this done many ways. I believe the correct way is using getDefaultViewModelProviderFactory(). But I have been using requireActivity().

     new ViewModelProvider(requireActivity(),getDefaultViewModelProviderFactory()).get(YourViewModel.class);
    

    |

     new ViewModelProvider(requireActivity()).get(YourViewModel.class);
    
              
    

    ViewModelProvider Docs

    Deprecated

    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-rc01'
    annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.2.0-rc01'
    

提交回复
热议问题