Attempt to invoke virtual method 'void android.arch.lifecycle.MutableLiveData.setValue(java.lang.Object)' on a null object reference
10,617
Update your function like this..
public class ActivationRepository {
public MutableLiveData<Boolean> status = new MutableLiveData<>();
public MutableLiveData<Boolean> getStatusCode(String activationCode) {
status.postValue(Boolean.valueOf(false));
return status;
}
Author by
Nikolas Bozic
Updated on June 05, 2022Comments
-
Nikolas Bozic about 2 years
I use Android architecture components and tried to instantiate viewmodel and Observe data from LiveData. But im getting the following error :
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; }
-
Nikolas Bozic over 6 yearsOmg, what a lame mistake, It works as this , thanks a lot
-
Santanu Sur over 6 yearsupdate ..the answer.. if it worked.. btw how r you ? i dint get time..could nt look at your git project.. :(
-
Nikolas Bozic over 6 yearsY i will check as correct, I am fine, how r u, I fixed that project, so no worries:)
-
woodii over 6 yearsthe problem was not
postValue()
which is prefered in general (because it runs not on the mainthread in comparison tosetValue()
). You just forgot to initialize your status object withnew MutableLiveData<>();
A somewhat misleading error message ;)