Android ViewModel 没有零参数构造函数 [英] Android ViewModel has no zero argument constructor

查看:25
本文介绍了Android ViewModel 没有零参数构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注 this 文档以了解 LiveData 和 ViewModel.在文档中,ViewModel 类具有构造函数,

public class UserModel extends ViewModel {私有 MutableLiveData<用户>用户;@Inject UserModel(MutableLiveData<用户>用户){this.user = 用户;}公共无效初始化(){如果(this.user != null){返回;}this.user = new MutableLiveData<>();}public MutableLiveData<用户>获取用户(){返回用户;}}

但是,当我运行代码时,出现异常:

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

<块引用>

Caused by: java.lang.RuntimeException: Cannot create an instance of class UserViewModel引起:java.lang.InstantiationException:类没有零参数构造函数

解决方案

当使用 ViewModelProviders 初始化 ViewModel 的子类时,默认情况下它需要你的 UserModel 类具有零参数构造函数.在您的情况下,您的构造函数具有参数 MutableLiveData用户.

解决此问题的一种方法是为您的 UserModel 设置一个默认的无参数构造函数.

否则,如果您想为您的 ViewModel 类使用非零参数构造函数,您可能需要创建一个自定义的 ViewModelFactory 类来初始化您的 ViewModel 实例,该实例实现了 ViewModelProvider.Factory 接口.

我还没有尝试过,但这里有一个优秀的谷歌示例链接:github.com/googlesamples/android-architecture-components.具体看这个类/GithubViewModelFactory.java" rel="nofollow noreferrer">GithubViewModelFactory.java 用于 Java 代码和此类 GithubViewModelFactory.kt 对应的 Kotlin 代码.

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

解决方案

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.

这篇关于Android ViewModel 没有零参数构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆