ViewModelProviders is deprecated in 1.1.0

后端 未结 22 1418
说谎
说谎 2020-12-07 09:14

Looking at the Google docs for ViewModel, they show the below sample code on how to get a ViewModel:

val model = ViewModelProviders         


        
22条回答
  •  自闭症患者
    2020-12-07 09:56

    This answer is for Java but you can understand main point. Solution is that you need use ViewModelProvider because ViewModelProviders deprecated:

    //Do not forget import it.
    import androidx.lifecycle.AndroidViewModel;
    
    ViewModelProvider.AndroidViewModelFactory(getApplication()).create(YourViewModel.class);
    

    Example usage is:

    YourViewModel yourViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(YourViewModel.class);
    

    Also, do not forget update Gradle Dependencies: Check here for last versions of them

    implementation 'androidx.lifecycle:lifecycle-viewmodel:2.2.0'
    annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.2.0'
    

    !!! However, be careful because some answers recommend this solution but it did not work for me:

    yourViewModel = new ViewModelProvider(this).get(YourViewModel.class);
    

    Because when I used this way, I got below Error Message:

    Caused by: java.lang.RuntimeException: Cannot create an instance of class com.canerkaseler.mvvmexample.ViewModel

    @canerkaseler

提交回复
热议问题