android - 从 FirebaseDatabse 收集所有数据并调用 notifyDataSetChanged() 一次
问题描述
简而言之:我有一个用户 ID 列表,我想遍历数据库并找到这些用户的配置文件并将它们放在列表中。但是我有一个问题如下:
final List<Friend> friendsProfiles = new ArrayList<>();
for (final FriendId friendId : friendIds) {
mUserRef.child(friendId).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// Get the friend profile
Friend friend = dataSnapshot.getValue(Friend.class);
// Add to the list
friendsProfiles.add(friend);
// The problem is here, because its called as many times as the size of
// the friendIds list. loadnewData() contains notifyDataSetChanged()
mFriendsFragment.loadNewData(friendsProfiles);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
// It gives 0, because it's called before onDatachange()
// So I can't call loadNewData() here
Log.d(TAG, updatedFriendsRequestList.size());
如何以良好,正确的方式做到这一点?
解决方案
您可以简单地计算已经加载了多少,然后notifyDataSetChanged()
仅在加载最后一个后才调用:
final List<Friend> friendsProfiles = new ArrayList<>();
for (final FriendId friendId : friendIds) {
mUserRef.child(friendId).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// Get the friend profile
Friend friend = dataSnapshot.getValue(Friend.class);
// Add to the list
friendsProfiles.add(friend);
if (friendsProfiles.size() == friendIds.length) {
mFriendsFragment.loadNewData(friendsProfiles);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors, as they break the logic of your app
}
});
}
推荐阅读
- docker - Windows10 主页上的 Docker - 在 docker 容器内连接到 docker 引擎
- mysql - 从库存数据库中高效查询产品变体(避免 EAV)
- javascript - 确保用户在更新后获得最新版本网站的正确方法
- python - 根据 pandas 的每日回报计算每月回报(加元)
- html - 更改字体真棒圆圈图标的背景颜色
- apache-nifi - 来自 SplitRecord 处理器 Nifi 的运行记录数
- node.js - 如何使用 google puppeteer 保存完整的网页?
- c# - Windows 窗体 Web 浏览器控制缩放级别
- angular - 仅针对 SonarTS 而不是 TSLint 跳过 .spec 文件
- firebase - 如何在firebase控制台中删除匿名授权用户?