尝试在空对象引用上调用虚拟方法 'void android.arch.lifecycle.MutableLiveData.setValue(java.lang.Object)'
Attempt to invoke virtual method 'void android.arch.lifecycle.MutableLiveData.setValue(java.lang.Object)' on a null object reference
我使用 Android 架构组件并尝试实例化视图模型并从 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) {
}
});
}
ActivationViewModel class:
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);
}
}
ActivationRepository class:
public class ActivationRepository {
public MutableLiveData<Boolean> status;
public MutableLiveData<Boolean> getStatusCode(String activationCode) {
status.setValue(Boolean.valueOf(false));
return status;
}
像这样更新你的函数..
public class ActivationRepository {
public MutableLiveData<Boolean> status = new MutableLiveData<>();
public MutableLiveData<Boolean> getStatusCode(String activationCode) {
status.postValue(Boolean.valueOf(false));
return status;
}
我使用 Android 架构组件并尝试实例化视图模型并从 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) {
}
});
}
ActivationViewModel class:
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);
}
}
ActivationRepository class:
public class ActivationRepository {
public MutableLiveData<Boolean> status;
public MutableLiveData<Boolean> getStatusCode(String activationCode) {
status.setValue(Boolean.valueOf(false));
return status;
}
像这样更新你的函数..
public class ActivationRepository {
public MutableLiveData<Boolean> status = new MutableLiveData<>();
public MutableLiveData<Boolean> getStatusCode(String activationCode) {
status.postValue(Boolean.valueOf(false));
return status;
}