首页 > 解决方案 > 从 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());

如何以良好,正确的方式做到这一点?

标签: androidfirebasefirebase-realtime-databaseandroid-recyclerview

解决方案


您可以简单地计算已经加载了多少,然后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
        }
    });
}

推荐阅读