Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

mvvm - Android ViewModel has no zero argument constructor

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While initializing subclasses of ViewModel using ViewModelProviders, by default it expects your UserModel class to have a zero argument constructor. In your case your constructor has the 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 implements the ViewModelProvider.Factory interface.

I have not tried this yet, but here's a link to an excellent Google sample for this: github.com/googlesamples/android-architecture-components. Specifically, check out this class GithubViewModelFactory.java for Java code and this class GithubViewModelFactory.kt for the corresponding Kotlin code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...