Cannot Create An Instance Of Class Viewmodel In Kotlin
Solution 1:
When you are initialising the ViewModel through ViewModelProviders without a factory, this means that you can only instantiate a ViewModel which has no constructor arguments. Like this:
viewmodel = ViewModelProviders.of(this).get(SettingsViewModel::class.java)
Notice that you cannot pass arguments to a .class call because you are not calling the constructor
Since your ViewModel has constructor arguments you need to implement a ViewModelProvider.Factory in order to be able to retrieve its instance with given parameters.
Here is a reference to android devs: https://developer.android.com/reference/android/arch/lifecycle/ViewModelProvider
Here refers to an article that can give you a insight on how to implement the factory: https://medium.com/@marco_cattaneo/android-viewmodel-and-factoryprovider-good-way-to-manage-it-with-dagger-2-d9e20a07084c
Solution 2:
in my case, I forget to add
AndroidInjection.inject(this);
in my activity like this :
@Override
public void onCreate(Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Post a Comment for "Cannot Create An Instance Of Class Viewmodel In Kotlin"