'ViewModelProviders' is deprecated. Java solution?

2.2k Views Asked by At

'ViewModelProviders' is deprecated from androidx.lifecycle:lifecycle-*:2.2.0-alpha03 https://developer.android.com/jetpack/androidx/releases/lifecycle#2.2.0-alpha03 Here is solution for Kotlin 'ViewModelProviders' is deprecated. After upgrading lifecycle-extensions:2.1.0 to 2.2.0-alpha05 But what is Java version of that? ViewModelProvider(this).get(MyViewModel.class) not work for Java.

3

There are 3 best solutions below

0
On

Generic Example (up to android.arch.lifecycle:extensions:1.1.0). it is deprecated from 1.1.1,

MyViewModel myViewModel = new ViewModelProviders.of(this, new MyViewModelFactory(this.getApplication(), "Your string parameter")).get(MyViewModel.class);

Generic Example (for android.arch.lifecycle:extensions:1.1.1)

MyViewModel myViewModel = new ViewModelProvider(this, viewModelFactory).get(MyViewModel.class);

OR, Use ViewModelStore link

MyViewModel myViewModel = new ViewModelProvider(getViewModelStore(), viewModelFactory).get(MyViewModel.class);
0
On

ViewModelProviders.of(this).get(MyViewModel.class); - deprecated

new ViewModelProvider(this).get(MyViewModel.class); - correct

Thanks @EpicPandaForce !

0
On

You can also create a CREATOR object for your ViewModel and call this object from your activity this object will act as a factory object that you can call as you call any ViewModelFactory.

ViewModelProviders.of(this, ViewModelFactoryObject).get(ViewModel::class.java).apply{}