gpt4 book ai didi

android - 从 FirebaseDatabse 收集所有数据并调用一次 notifyDataSetChanged()

转载 作者:行者123 更新时间:2023-11-29 16:33:34 25 4
gpt4 key购买 nike

简而言之:我有一个用户 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
}
});
}

关于android - 从 FirebaseDatabse 收集所有数据并调用一次 notifyDataSetChanged(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53284983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com