Cannot resolve symbol ViewModelProviders

ashwin mahajan picture ashwin mahajan · Jun 5, 2018 · Viewed 11.7k times · Source

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"
}

enter image description here

Answer

CommonsWare picture CommonsWare · Jun 5, 2018

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:

android.arch.lifecycle:extensions:1.1.1 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)