I have LiveData object that I perform a Transformations.map() on to apply a formula to the data before notifying any observers. However I have a delete function on the UI that deletes the object from the DB (room) and when the LiveData gets updated, the Transformation.map() causes a crash with the following error "Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference" since the object it was observing has been removed from the DB
I have tried also removing the observer after the first update but it is still throwing the same error.
I've posted the code below, anyone have any ideas to solve it?
public LiveData<String> getTotalValue() {
if (totalValueLiveData == null) {
loadTotalValue();
}
totalValue = Transformations.map(totalvalueLiveData, total -> String.format(Locale.getDefault(), "%.1f", UtilUserUnitsConverter.convertValue(total, userUnit)));
return totalValue;
}
final Observer<String> getTotalValueObserver = new Observer<String>() {
@Override
public void onChanged(@Nullable String totalValue) {
if (totalValue != null) {
totalValueTv.setText(totalValue);
}
viewModel.getTotalValue().removeObserver(getTotalValueObserver);
}
};
viewModel.getTotalValue().observe(this, getTotalValueObserver);
答案 0 :(得分:0)
这个问题已经有4个月了,但是问题很可能来自您的viewModel.getTotalValue()
方法。
Transformations.map()
方法每次调用都会创建一个新的LiveData对象,这意味着每次调用viewModel.getTotalValue()
都会得到一个全新的对象。
换句话说:您在两个不同的对象上调用removeObserver
和observe
而没有注意到。