问题描述
我使用ViewPager2和Tabs嵌套了片段,并且使用RecyclerView
将数据加载到MutableLiveData
中。一切正常,直到我更新了Firebase实时数据库中的某些内容(例如某些食品的名称)。因此,如果我有10个类别项,每个类别有5种食物,并且我更新了1种食物的名称,那么我的屏幕闪烁和10个新类别就被添加了,每个类别有5种食物,现在我共有20个类别 > ..
所需的行为将是:更新数据,没有屏幕闪烁,仅更新更改的项目,而无需再次添加所有类别和食物列表
那我如何才能实现MutableLiveData更新刚刚更改的项目,而不是整个列表?
ViewModel
public class MenuViewModel extends ViewModel implements
ICategoryCallbackListener,IFoodCallbackListener {
private MutableLiveData<String> messageError = new MutableLiveData<>();
private MutableLiveData<List<CategoryModel>> categoryListMutable;
private ICategoryCallbackListener categoryCallbackListener;
private MutableLiveData<List<FoodModel>> foodListMutable;
private IFoodCallbackListener foodCallbackListener;
public MenuViewModel() {
categoryCallbackListener = this;
foodCallbackListener = this;
}
public MutableLiveData<List<CategoryModel>> getCategoryListMutable() {
if(categoryListMutable == null)
{
categoryListMutable = new MutableLiveData<>();
messageError = new MutableLiveData<>();
loadCategories();
}
return categoryListMutable;
}
public MutableLiveData<List<FoodModel>> getFoodListMutable(String key) {
if(foodListMutable == null)
{
foodListMutable = new MutableLiveData<>();
messageError = new MutableLiveData<>();
loadFood(key);
}
return foodListMutable;
}
public void loadCategories() {
List<CategoryModel> tempList = new ArrayList<>();
DatabaseReference categoryRef = FirebaseDatabase.getInstance()
.getReference(Common.RESTAURANT_REF)
.child(Common.currentRestaurant.getUid())
.child(Common.CATEGORY_REF);
categoryRef.keepSynced(true);
categoryRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot itemSnapShot: snapshot.getChildren())
{
CategoryModel categoryModel=itemSnapShot.getValue(CategoryModel.class);
if(categoryModel != null)
categoryModel.setMenu_id(itemSnapShot.getKey());
tempList.add(categoryModel);
}
categoryCallbackListener.onCategoryLoadSuccess(tempList);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
categoryCallbackListener.onCategoryLoadFailed(error.getMessage());
}
});
}
public void loadFood(String key) {
List<FoodModel> tempList = new ArrayList<>();
DatabaseReference foodRef = FirebaseDatabase.getInstance()
.getReference(Common.RESTAURANT_REF)
.child(Common.currentRestaurant.getUid())
.child(Common.CATEGORY_REF)
.child(key)
.child(Common.FOOD_REF);
foodRef.keepSynced(true);
foodRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot itemSnapShot: snapshot.getChildren())
{
FoodModel foodModel = itemSnapShot.getValue(FoodModel.class);
tempList.add(foodModel);
}
foodCallbackListener.onFoodLoadSuccess(tempList);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
foodCallbackListener.onFoodLoadFailed(error.getMessage());
}
});
}
public MutableLiveData<String> getMessageError() {
return messageError;
}
@Override
public void onCategoryLoadSuccess(List<CategoryModel> categoryModels) {
categoryListMutable.setValue(categoryModels);
}
@Override
public void onCategoryLoadFailed(String message) {
messageError.setValue(message);
}
@Override
public void onFoodLoadSuccess(List<FoodModel> foodModels) {
foodListMutable.setValue(foodModels);
}
@Override
public void onFoodLoadFailed(String message) {
messageError.setValue(message);
}
MenuFragment
public class MenuFragment extends Fragment {
public static final String ARG_MENU = "menu";
private MenuViewModel menuViewModel;
//Irrelevant code
MyFoodListAdapter adapter;
@Override
public View onCreateView(@NonNull LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
menuViewModel = new ViewModelProvider(this).get(MenuViewModel.class);
View root = inflater.inflate(R.layout.fragment_menu,container,false);
//Irrelevant code
return root;
}
@Override
public void onViewCreated(@NonNull View view,@Nullable Bundle savedInstanceState) {
Bundle args = getArguments();
menuViewModel.getFoodListMutable(Objects.requireNonNull(args)
.getString(ARG_MENU))
.observe(getViewLifecycleOwner(),foodModels -> {
adapter = new MyFoodListAdapter(getContext(),foodModels);
recycler_menu.setAdapter(adapter);
});
}
}
类别模型
public class CategoryModel {
private String menu_id,name,image,background;
private Long numberOfOrders;
List<FoodModel> foods;//Setters and Getters}
解决方法
如果将ValueEventListener
附加到某个位置,则每次在该位置下进行任何修改时,都会调用该位置的所有数据的快照。
只要发生这种情况,您的onDataChange
就会将快照中的项目添加到tempList
中。因此,在初始加载时会添加10个类别。然后,当有更改时,它将再次添加它们,您最终得到20个类别。
摆脱重复项目的最简单方法是在将项目添加到列表之前清除列表:
categoryRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
tempList.clear();
for(DataSnapshot itemSnapShot: snapshot.getChildren())
{
CategoryModel categoryModel=itemSnapShot.getValue(CategoryModel.class);
if(categoryModel != null)
categoryModel.setMenu_id(itemSnapShot.getKey());
tempList.add(categoryModel);
}
categoryCallbackListener.onCategoryLoadSuccess(tempList);
}
这可以消除重复项,但是在您迫使Android重新绘制整个列表时,仍然可能会导致闪烁。如果您还想摆脱这种情况,请考虑使用addChildEventListener
。使用该类型的侦听器,您会收到有关单个子节点的更改的通知,并可以使用该信息对tempList
执行最小的更新,然后您还可以通过调用notifyItemChanged
告诉Android执行该更新。和类似的方法。这几乎是FirebaseUI中的适配器所做的。