Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot resolve symbol ViewModelProviders on AppCompatActivity

People also ask

How do I use ViewModelProvider on Android?

If your ViewModel has dependencies or arguments and you want to create your ViewModel instance, then you should create your custom ViewModelProvider. Factory and pass the dependency or arguments through the ViewModel constructor and give a value to the ViewModelProvider. Factory instance.


I didn't have both dependencies in my build, hence the problem.

implementation "android.arch.lifecycle:extensions:1.1.0"
implementation "android.arch.lifecycle:viewmodel:1.1.0"

Thanks @Muthukrishnan Rajendran


If you are using androidx you need this:

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

android.arch.lifecycle:extensions is deprecated use

def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"

Create instance of viewmodel like this:

Java

Yourclass obj = new ViewModelProvider(context).get(ClassViewModel.class);

Kotlin

var obj = ViewModelProvider(context).get(ClassViewModel::class.java)

If you are using compiled sdk version 28 or higher you only need to add single dependecy to get ViewModel and LiveData

dependencies {
    //...
    def lifecycle_version = "1.1.1"

    // ViewModel and LiveData
    implementation "android.arch.lifecycle:extensions:$lifecycle_version"
}