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

Exception or error:

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?

How to solve:

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) {
                }
            });

###

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
myRef.addValueEventListener(new ValueEventListener() {
 @Override
 public void onDataChange(DataSnapshot dataSnapshot) {
    for(DataSnapshot item_snapshot:dataSnapshot.getChildren()) {

      Log.d("item id ",item_snapshot.child("item_id").getValue().toString());
      Log.d("item desc",item_snapshot.child("item_desc").getValue().toString());
     }
  }
}

###

Let say you have a reference to the node users, you can iterate through the nodes as follows:

reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot child : dataSnapshot.getChildren() ){
                // Do magic here
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {}
    });

Note that the DataSnapshot child inside the for loop will have the UIDs as key, not users.

Leave a Reply

Your email address will not be published. Required fields are marked *