ashwin mahajan
ashwin mahajan

Reputation: 1782

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

Upvotes: 7

Views: 13686

Answers (4)

Ian
Ian

Reputation: 334

ViewModelProviders is now deprecated. Use ViewModelProvider instead.

Upvotes: 2

EAM
EAM

Reputation: 401

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.

Upvotes: 2

lyy
lyy

Reputation: 21

If you are configuring in libary, you can modify the implementation to api

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006664

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)

Upvotes: 14

Related Questions