Firebase for Android, How can I loop through a child (for each child = x do y)

Tags: , , ,



This is what my test looks like:

enter image description here

I won’t use the fields above, it’s just a dummy. But I would like to go through all the children on “users” and for each email return a:

System.out.println(emailString);

The only way I found of listing an object is using firebaseAdapter, is there another way of doing it?

Answer

The easiest way is with a ValueEventListener.

    FirebaseDatabase.getInstance().getReference().child("users")
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        User user = snapshot.getValue(User.class);
                        System.out.println(user.email);
                    }
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });

The User class can be defined like this:

class User {
  private String email;
  private String userId;
  private String username;
  // getters and setters...
}


Source: stackoverflow