ViewModelProviders is deprecated in 1.1.0
I use lifecycle-extensions 2.2.0
version:
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
It should work, using ViewModelProvider
constructor.
// With ViewModelFactory
val viewModel = ViewModelProvider(this, YourViewModelFactory).get(YourViewModel::class.java)
//Without ViewModelFactory
val viewModel = ViewModelProvider(this).get(YourViewModel::class.java)
2020/5/15 Update
I found another elegant way to achieve this, Android KTX can help
implementation "androidx.fragment:fragment-ktx:1.2.4"
val viewmodel: MYViewModel by viewModels()
val viewmodel: MYViewModel by viewModels { myFactory } //With factory
Ref: https://developer.android.com/reference/kotlin/androidx/fragment/app/package-summary#viewmodels
2020/06/25: corrected the case of the delegate
Import
Deprecated From:
import androidx.lifecycle.ViewModelProviders;
To:
import androidx.lifecycle.ViewModelProvider;
Using
Deprecated From:
ViewModelProviders.of(this, provider).get(VM::class.java)
To:
ViewModelProvider(this, provider).get(VM::class.java)
As of 2.2.0. the lifecycle-extensions has been deprecated. Refer to Google Documentation.
This is the cut from the page:
The APIs in lifecycle-extensions have been deprecated. Instead, add dependencies for the specific Lifecycle artifacts you need.
The new libraries are:
// ViewModel and lifecycle support for java
implementation "androidx.lifecycle:lifecycle-viewmodel:${versions.lifecycle}"
implementation "androidx.lifecycle:lifecycle-livedata:${versions.lifecycle}"
// ViewModel and lifecycle support for kotlin
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:${versions.lifecycle}"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:${versions.lifecycle}"
The new code for JAVA:
viewModel = new ViewModelProvider(this).get(MyViewModel.class);
Or for Kotlin:
viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
As @FantasyFang mentioned in his answer, use the lastest version for the lifecycle:lifecycle-extensions
which in this moment is 2.2.0-alpha03
. So you should add in your build.gradle file the following line:
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-alpha03'
For those who are using Java, to solve this, pass those arguments directly to ViewModelProvider's constructor:
MyViewModel viewModel = new ViewModelProvider(this, myViewModelFactory).get(MyViewModel.class);
Or if you don't use a factory, simply use:
MyViewModel viewModel = new ViewModelProvider(this).get(MyViewModel.class);
Without passing your the factory object.