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

后端 未结 4 1692
花落未央
花落未央 2020-12-24 02:45

This is what my test looks like:

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 eac

4条回答
  •  粉色の甜心
    2020-12-24 03:41

    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...
    }
    

提交回复
热议问题