I am working on Android ViewModel architecture component but I am getting the above mentioned error when trying to initialize a ViewModel in an AppCompatActivity.
import android.arch.lifecycle.ViewModelProviders;
ViewModelProviders.of(this).get(CounterViewModel.class);
There are a few questions and articles related to this, and they pointed towards adding the lifecycle:extensions
and lifecycle:viewmodel
dependencies in the app gradle file, but I am still getting the error.
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "android.arch.lifecycle:viewmodel:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
The package android.arch.lifecycle does not contain the class ViewModelProviders
and it only has ViewModelProvider
class.
What else needs to be added to access the ViewModelProviders
class?
Edit :
Dependencies in app/build.gradle:
dependencies {
implementation project(':lifecycle')
implementation project(':base')
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "android.arch.lifecycle:viewmodel:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
}
android.arch.lifecycle:extensions:1.1.1
definitely has android.arch.lifecycle.ViewModelProviders
. You can see it in Android Studio, if you open the "External Libraries" portion of the project tree and examine the library contents:
Some possible reasons for not finding the import
include:
You have implementation "android.arch.lifecycle:extensions:1.1.1"
in the wrong place (it should be in the dependencies
closure of the module's build.gradle
file, such as app/build.gradle
)
You did not sync Android Studio with the Gradle build files (you are normally prompted to do this, but you can do it manually from File > Sync Project with Gradle Files from the Android Studio main menu)
You do not need both lifecycle:extensions
and lifecycle:viewmodel
in your build.gradle file, remove
implementation "android.arch.lifecycle:viewmodel:1.1.1"
and it should be fine now. Also, you may want to migrate to AndroidX and use the 2.0.0 versions of the library.
ViewModelProviders
is now deprecated. Use ViewModelProvider
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With