Android ViewModel has no zero argument constructor

Prabin Timsina picture Prabin Timsina · May 26, 2017 · Viewed 33.5k times · Source

I am following this documentation to learn about LiveData and ViewModel. In the doc, the ViewModel class has constructor as such,

public class UserModel extends ViewModel {
  private MutableLiveData<User> user;

  @Inject UserModel(MutableLiveData<User> user) {
    this.user = user;
  }

  public void init() {
    if (this.user != null) {
      return;
    }
    this.user = new MutableLiveData<>();
  }

  public MutableLiveData<User> getUser() {
    return user;
  }
}

However, when I run the code, I get exception:

final UserViewModelviewModel = ViewModelProviders.of(this).get(UserViewModel.class);

Caused by: java.lang.RuntimeException: Cannot create an instance of class UserViewModel Caused by: java.lang.InstantiationException: java.lang.Class has no zero argument constructor

Answer

Shahbaz Ahmed picture Shahbaz Ahmed · May 26, 2017

While initializing subclasses of ViewModel using ViewModelProviders, by default it expects your UserModel class to have zero argument constructor. In your case your constructor has argument MutableLiveData<User> user

One way to fix this is to have a default no arg constructor for your UserModel

Otherwise, if you want to have a non zero argument constructor for your ViewModel class, you may have to create a custom ViewModelFactory class to initialise your ViewModel instance, which will implement ViewModelProvider.Factory interface.

I have not tried this yet, but here is the link to excellent sample from google for the same: github.com/googlesamples/android-architecture-components. Specifically, checkout this class GithubViewModelFactory.java for Java code and this class GithubViewModelFactory.kt for corresponding Kotlin code