Looking at the Google docs for ViewModel
, they show the below sample code on how to get a ViewModel
:
val model = ViewModelProviders
Yes @Tarek, it is deprecated. Use now with AndroidX:
val yourViewModel = ViewModelProvider.NewInstanceFactory().create(YourVideoModel::class.java)
Use ViewModelProvider directly instead of user ViewModelProviders.of() as mentioned in the docs.
ViewModelProvider(this).get(XViewModel::class.java)
https://developer.android.com/reference/androidx/lifecycle/ViewModelProviders
I'm no expert but i have a line of code that solved my problem in Java. Hope this helps someone.
viewModel =
new ViewModelProvider
.AndroidViewModelFactory(getApplication())
.create(ViewModel.class);
As i said i would love to provide more details, but this fixed this problem for me.
I'm using android X
and also had this issue.
First of all, you should add these dependencies to your Gradle
:
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
In my case, the $lifecycle_version was 2.2.0-rc02
Second:
The import for the ViewModelProvider
should be:
import androidx.lifecycle.ViewModelProvider
Than you can initial your vIewModel like the examples below:
val viewModel = ViewModelProvider(this, YourFactoryInstace).get(MainViewModel::class.java)
val viewModel = ViewModelProvider(this).get(MainViewModel::class.java)