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

标签 android android-livedata

我使用 Android 架构组件并尝试从 LiveData 实例化 View 模型和观察数据。但我收到以下错误:

ActivationFragment.class:

@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) {
        } 
    });
}

激活 View 模型类:
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 类:
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 - 尝试在空对象引用上调用虚拟方法 'void android.arch.lifecycle.MutableLiveData.setValue(java.lang.Object)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48901575/

相关文章:

android - 如何在另一个 Activity 中的ImageButton单击上播放声音?

android - 安卓应用中的广告,值得吗?

Android Jetpack Compose mutableStateListOf 不做重组

android - LiveDataobserveForever不起作用

Android MVVM Livedata 最佳实践

Android in app billing 声称不支持使用示例代码

android - 移动图书馆或图片库示例

android - 如何将两个 mutablelivedata 的结果合二为一

android - liveData的onChanged方法观察多次调用

android - 添加 : annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.0.0" 后 list 合并失败