我想展示一份可排序的餐馆名单。当我使用一个简单的LiveData时,它起了作用,但是我得到了一个NullPointerException,因为我将它改为了一个mediatorLiveData。
在片段中,我使用这些行来观察mediatorLiveData
vm.getAllRestaurantsWithOrderMediatorLD().observe(getViewLifecycleOwner(), listRestaurants -> {
datas.clear();
datas.addAll(listRestaurants);
adapter.notifyDataSetChanged();
});
在这里,viewmodel类:
public class ListRestaurantsViewModel extends ViewModel {
private final RestaurantRepository restaurantRepository;
private final SortRepository sortRepository;
private final MutableLiveData<List<RestaurantViewState>> allRestaurantsViewStateLD = new MutableLiveData<>();
private final MutableLiveData<SortRepository.OrderBy> orderLiveData = new MutableLiveData<>();
private final MediatorLiveData<List<RestaurantViewState>> allRestaurantsWithOrderMediatorLD;
Context ctx;
public ListRestaurantsViewModel(RestaurantRepository restaurantRepository, SortRepository sortRepository, Context ctx) {
this.ctx = ctx;
this.restaurantRepository = restaurantRepository;
this.sortRepository = sortRepository;
allRestaurantsWithOrderMediatorLD = new MediatorLiveData<>();
allRestaurantsWithOrderMediatorLD.addSource(getAllRestaurantsViewStateLD(), value -> allRestaurantsWithOrderMediatorLD.setValue(value));
allRestaurantsWithOrderMediatorLD.addSource(getOrderLiveData(), order -> {
List<RestaurantViewState> restaurants = getAllRestaurantsViewStateLD().getValue();
if (restaurants != null && !restaurants.isEmpty()) {
List<RestaurantViewState> newList = new ArrayList<>();
if (order == SortRepository.OrderBy.DISTANCE)
newList =
Stream.of(restaurants).sorted((a, b) -> a.getDistance() - b.getDistance()).toList();
else if (order == SortRepository.OrderBy.RATING)
newList = Stream.of(restaurants).sorted((a, b) -> Double.compare(a.getStarsCount(),
b.getStarsCount())).toList();
allRestaurantsWithOrderMediatorLD.setValue(newList);
}
}
);
}
public MediatorLiveData<List<RestaurantViewState>> getAllRestaurantsWithOrderMediatorLD() {
return allRestaurantsWithOrderMediatorLD;
}
public LiveData<SortRepository.OrderBy> getOrderLiveData() {
return sortRepository.getOrderLiveData();
}
public LiveData<List<RestaurantViewState>> getAllRestaurantsViewStateLD() {
return Transformations.map(restaurantRepository.getRestaurantsLiveData(), restaurantsList -> {
List<RestaurantViewState> restaurantViewStates = new ArrayList<>();
for (Restaurant r : restaurantsList) {
restaurantViewStates.add(new RestaurantViewState(
r.getId(),
r.getName(),
r.getType(),
r.getAdress(),
r.getImage()
)
);
}
return restaurantViewStates;
});
}
这是错误,我得到了java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.lifecycle.LiveData.observeForever(androidx.lifecycle.Observer)' on a null object reference
如果我观察到片段中的livedata getAllRestaurantsViewStateLD(),我没有错误,所以我认为在使用mediatorLiveData时没有得到一些东西,您知道它是什么吗?
发布于 2021-12-16 16:55:19
崩溃是在调用observeForever
时发生的,但是您的代码片段并没有显示您正在使用它。所以问题就在别的地方。
https://stackoverflow.com/questions/70382670
复制相似问题