-1

i am trying to add the keys from a firebase database to an arraylist in my onDataChange method.

        mDatabase = FirebaseDatabase.getInstance().getReference("events");
    mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if(dataSnapshot.exists()) {
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

                            String event = snapshot.getKey();
                            Log.d("did it work??", event);
                            eventList.add(event);
                        }
                    }
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });

when i log event it'll print but its not adding to eventList arrayList

hooray4horus
  • 99
  • 2
  • 12

2 Answers2

3

If you want the entire snapshot to be delivered to the listener, use either addValueEventListener or addListenerForSingleValueEvent.

If you use addValueEventListener, the listener will be called with the initial snapshot and again if the database changes.

And if you use addListenerForSingleValueEvent, the listener will be called only once with the initial snapshot.

The snapshot received by the listener will include all of the children. To iterate them you would do something like this:

@Override
public void onDataChange(DataSnapshot snapshot) {
    ArrayList<String> ids = new ArrayList<String>();
    for (DataSnapshot childSnapshot: snapshot.getChildren()) {
        ids.add(childSnapshot.getValue().toString());
    }
}
geekfreak.xyz
  • 90
  • 1
  • 9
  • 1
    hey awesome thanks. how can i reference ids outside of the onDataChange method. i tried declaring ids as globally but it didnt work – hooray4horus Jun 23 '17 at 16:55
1

This is happening because onDataChange method is called asynchronously. This means that the statement that adds the strings to the ArrayList is executed before onDataChange() method has been called. That's why your list is empty outside that method. So in order to use that ArrayList, you need to declare and use it inside the onDataChange() method.

ArrayList<String> ids = new ArrayList<>();

If you want to use that ArrayList outside the onDataChange() method, than see my answer from this post.

Hope it helps.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193