Collect all data from FirebaseDatabse and call notifyDataSetChanged() once

筅森魡賤 提交于 2019-12-11 06:07:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!