从FirebaseDatabse收集所有数据,然后一次调用notifyDataSetChanged()

时间:2018-11-13 16:05:44

标签: android firebase firebase-realtime-database android-recyclerview recycler-adapter

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

如何以一种合适的方式来做到这一点?

1 个答案:

答案 0 :(得分:3)

您可以简单地计算已加载的数量,然后仅在加载了最后一个后调用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
        }
    });
}