尝试在空对象引用上调用虚拟方法'void android.arch.lifecycle.MutableLiveData.setValue(java.lang.Object)'

Nik*_*zic 3 android android-livedata

我使用Android体系结构组件,并尝试实例化viewmodel和从LiveData观察数据。但是我收到以下错误:

ActivationFragment.clas:

@OnClick(R.id.btn_activation)
public void onEvaluateClick(Button v) {
    maActivationCode = etActivation.getText().toString();
    mActiationViewModel.getsatusCode(maActivationCode).observe(this, new Observer<Boolean>() {
        @Override
        public void onChanged(@Nullable Boolean aBoolean) {
        } 
    });
}
Run Code Online (Sandbox Code Playgroud)

ActivationViewModel类:

public class ActivationViewModel  extends ViewModel{

public ActivationRepository activationRepository;

public ActivationViewModel(ActivationRepository activationRepository) {
    this.activationRepository = activationRepository;
}

public LiveData<Boolean> getsatusCode(String activationCode) {
    return (LiveData<Boolean>)  activationRepository.getStatusCode(activationCode);
}
Run Code Online (Sandbox Code Playgroud)

}

ActivationRepository类:

public class ActivationRepository {

public MutableLiveData<Boolean> status;

public MutableLiveData<Boolean> getStatusCode(String activationCode) {
    status.setValue(Boolean.valueOf(false));
    return status;
}
Run Code Online (Sandbox Code Playgroud)

San*_*Sur 7

像这样更新您的功能。

public class ActivationRepository {

public MutableLiveData<Boolean> status = new MutableLiveData<>();

 public MutableLiveData<Boolean> getStatusCode(String activationCode) {
    status.postValue(Boolean.valueOf(false));
    return status;
}
Run Code Online (Sandbox Code Playgroud)

  • 问题不是通常首选的`postValue()`(因为与`setValue()`相比,它不在主线程上运行)。您只是忘了用new new MutableLiveData &lt;&gt;();初始化状态对象;有点误导性的错误消息;) (2认同)