java - Recyclerview 不使用 MVVM 在 Fragment 中显示数据
问题描述
我正在从 firebase 加载数据,我想使用 MVVM 在 recyclerview 中显示它我从 firebase 检索数据并且它工作正常。但我想用来 adapter.notifyDataSetChanged();
更新 Repo 类中的 recyclerview 这是我的 repo 类:
public class CategoriesRepo {
private static CategoriesRepo instance;
private final ArrayList<Cat> categoriesModel = new ArrayList<>();
private DatabaseReference dbCategories;
public static CategoriesRepo getInstance() {
if (instance == null) {
instance = new CategoriesRepo();
}
return instance;
}
public MutableLiveData<ArrayList<Cat>> getCategories() {
loadCats();
MutableLiveData<ArrayList<Cat>> categories = new MutableLiveData<>();
categories.setValue(categoriesModel);
return categories;
}
private void loadCats() {
dbCategories = FirebaseDatabase.getInstance().getReference("categories");
dbCategories.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NotNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.getKey();
// this is not showing in recyclerview
categoriesModel.add(new Cat("Name", 1));
Log.d("TAGD", "onDataChange: " + ds.getKey() + " " + categoriesModel.size());
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
有没有办法使用 MVVM 更新 recyclerview?
解决方案
LiveData
将在值更改时提供回调,即setValue
或postValue
。因此,您需要在获取数据之后而不是之前设置该值。
public class CategoriesRepo {
private static CategoriesRepo instance;
private DatabaseReference dbCategories;
private MutableLiveData<ArrayList<Cat>> categories = new MutableLiveData<>();
public static CategoriesRepo getInstance() {
if (instance == null) {
instance = new CategoriesRepo();
}
return instance;
}
public MutableLiveData<ArrayList<Cat>> getCategories() {
loadCats();
return categories;
}
private void loadCats() {
dbCategories = FirebaseDatabase.getInstance().getReference("categories");
dbCategories.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NotNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
ArrayList<Cat> categoriesModel = new ArrayList<>()
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.getKey();
categoriesModel.add(new Cat("Name", 1));
}
categories.setValue(categoriesModel);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
这应该工作。您还必须通过数据加载处理错误状态。通过这个线程来处理所有的状态。
推荐阅读
- python - /brooklyn/beachs 的 Django TypeError
- sql - 使用 PostgreSQL 计算年同比增长
- python - 齿轮下的命令不显示
- unity3d - 将 CAD(步骤 .stp)文件拆分为单独的部分,然后可以将其导入 Unity 并相对于彼此移动?
- anylogic - AnyLogic:具有不同优先级的两个客户类别
- google-apps-script - Google Script - 将二维数组的一部分应用于工作表
- android - 带有 Gradle 7 的 CMake 二进制目录
- mysql - 根据同一张表的结果优化选择表中的所有行?
- python - 在 Python 中创建一个以特定方式重新排列其他列表的新列表
- python - 使用python PIL批量平铺图像,按文件夹重复填充背景图像