Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot resolve symbol ViewModelProviders

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

like image 977
ashwin mahajan Avatar asked Jun 05 '18 12:06

ashwin mahajan


3 Answers

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)

like image 109
CommonsWare Avatar answered Nov 14 '22 18:11

CommonsWare


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.

like image 22
EAM Avatar answered Nov 14 '22 17:11

EAM


ViewModelProviders is now deprecated. Use ViewModelProvider instead.

like image 2
Ian Avatar answered Nov 14 '22 18:11

Ian