Recyclerview不显示数据片段使用MVVM



我正在从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将提供值变化的回调,即setValuepostValue。因此,您需要在获取数据之后而不是之前设置值。

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) {
}
});
}
}

这应该可以工作。此外,您必须处理数据加载时的错误状态。通过这个线程来处理所有的状态。

最新更新