I am using dagger2 library. whenever I am trying to run my project is says not able to create instance of view model class.
main activity where I am trying to create
I'm a proficient Android developer and I have used ViewModel 100s of times with no issue. Today I came across this issue. Spent hours and scrolled through various SO posts. Didn't get solved.
Then I saw that the package name in which I have the ViewModel contains new. Like this:
com.myapp.myfeature.new.feature
I changed new to neww for testing like this: com.myapp.myfeature.neww.feature
and it worked! I hope someone find it useful.
Extend AndroidViewModel from your ViewModel class.
public class YourViewModel extends AndroidViewModel {
public YourViewModel(Application application) {
super(application);
//Todo: ...
}
}
Need to add below code in all activity if you use multiple activity
AndroidInjection.inject(this);
The solution for me was injecting the activity because I was using Dagger2
AndroidInjection.inject(this);
Instead of:
mViewModel = ViewModelProviders.of(this).get(MoviesDataViewModel.class);
Perform:
mViewModel = ViewModelProviders.of(this, viewModelFactory).get(MoviesDataViewModel.class);
Replace:
private MoviesDataViewModel mViewModel;
with:
MoviesDataViewModel mViewModel;