问题
in brief: I have a list of users ID and I want to iterate over database and find profiles of those users and put them on the list. But I have a problem as follows:
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());
How to do it in the nice, proper way?
回答1:
You can simply count how many you've already loaded, and then call notifyDataSetChanged()
only once you've loaded the last one:
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
}
});
}
来源:https://stackoverflow.com/questions/53284983/collect-all-data-from-firebasedatabse-and-call-notifydatasetchanged-once