Skip to content
Advertisement

How to read data from firebase without specifying the child?

good day, here is my firebase real-time structure

  -User
      |
      |
      -3fh3s2q431yhn6v45
                        |
                        |
                        -phone: "+2348168xxxxx"
                        -name: "Amazinguser"
                        -status: "active"
                        -bio: "*no bio*"
      -64cdw2koysqwvydv45
                        |
                        |
                        -phone: "+2340768xxxxx"
                        -name: "Amazinguser23"
                        -status: "active"
                        -bio: "*no bio*"
      -g6a11qag9gj5urwzak
                        |
                        |
                        -phone: "+2344358xxxxx"
                        -name: "Amazinguser3"
                        -status: "active"
                        -bio: "*no bio*"

Here is my java code

FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference rf = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());

rf.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    User user = dataSnapshot.getValue(UserModel.class);

    //Futher implementation on user
  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    //Imlementation of errors
  }
});

The above code is the sample of my class which i used in reading the logged user data with its firebaseUser.getUid()

Question. How can i read all the User data all together without having to provide or use firebaseUser.getUid() in the child method ? Thanks.

Advertisement

Answer

By getReference("Users") you will get all list which is inside the User and with Datasnapshot loop you can list down each user. Here is the code:

DatabaseReference rf = FirebaseDatabase.getInstance().getReference("Users");
rf.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
  User user = userSnapshot.getValue(UserModel.class);
  //Futher implementation on user
}
  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    //Imlementation of errors
  }
});
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement