Could Not use ViewModelProvider in androidx JAVA

100 Views Asked by At

This question might look like an duplicate question but those questions didn't help me : (

Im using Java, AndroidX and Android Studio 3.6

I am trying to implement Room Database with LiveData, ViewModel and Lifecycle

But When I am initializing MyViewModelClass using ViewModelProviders.of(this).get()

I am Getting "Cannot resolve method get()" error Image Of the Error

So I searched on google and found to use another alternative class ViewModelProvider

But I can't even Import this class

While Importing I get "Cannot resolve symbol ViewModelProvider" [Image Of the Error]

My Gradle dependencies for lifecycle and room are


    implementation 'androidx.room:room-runtime:2.4.2'
    annotationProcessor 'androidx.room:room-compiler:2.4.2'

    implementation 'androidx.lifecycle:lifecycle-common-java8:2.6.2'
    implementation 'androidx.lifecycle:lifecycle-viewmodel:2.6.2'
    implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
    implementation 'androidx.lifecycle:lifecycle-livedata:2.6.2'
    implementation 'androidx.lifecycle:lifecycle-livedata-core:2.6.2'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2'

I tried Changing the Dependecy versions, creating new project

I don't understand what the problem is

If I made any mistake in implementing Please let me know

Thanks in advance : )

1

There are 1 best solutions below

0
Harshali On

As per official doc https://developer.android.com/reference/android/arch/lifecycle/ViewModelProviders ViewModelProviders.of() method is deprecated.
Please refer https://developer.android.com/reference/androidx/lifecycle/ViewModelProviders

For Java

// replace
viewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);

// with
vewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);

For kotlin reference

// replace 
viewModel = ViewModelProviders.of(this).get(MainActivityViewModel::class.java)

// with
viewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)

if you use kotlin you have one advantage of Lazy Initialization

private val viewModel: MainActivityViewModel by viewModels()