问题
I'm working with firebase in a android application and something strange ocurred, in my example I need two snapshots, 1 to get the users inside a list ( I use this snapshot to fill a arraylist of strings with the key of the user) and the other to compare to the users, the strange behavior is that my arraylist is empty after the first snapshot, I used logcat to check it and that Log inside the firstsnapshot returns me 1 as the size of the arraylist, the second returns me 0, dunno how it gets 0 again.
Here is my code:
private void prepareFriendList() {
myRef.child(id).child("FriendLists").child(group).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String keyUser;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Log.d("number:",snapshot.getKey());
keyUser = snapshot.getKey();
currentFriends.add(keyUser);
Log.d("hello",String.valueOf(currentFriends.size()));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
for(String s: currentFriends){
Log.d("idddd",s);
}
Log.d("hello",String.valueOf(currentFriends.size()));
myRef.child(id).child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
for(String item: currentFriends){
if (snapshot.getKey().equals(item)) {
usersList.add(user);
}
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mAdapter.notifyDataSetChanged();
}
I don't understand why that happens, since I'm adding the key inside the arraylist, any tip?
回答1:
This is happening because onDataChange is called asynchronously. This means that the statement that adds users to the list
is executed before onDataChange
has been called. That's why your list
is empty outside that method. So in order to use that lists, you need to use it inside the onDataChange()
method.
For other approach, please visit this post and this post.
Hope it helps.
来源:https://stackoverflow.com/questions/43612171/arraylist-gets-empty-after-first-snapshot