Home > Mobile >  Firebase - get childrens of children
Firebase - get childrens of children

Time:05-14

I am looking for a good solution to take data from a child of children.

As You can see in my "users" database i have nodes with users uid's, and in this nodes i have stored users data such as avatar, username etc. but i have problem with getting data from example "followers" node - So far I have been creating a new OnChildAddedListener in main OnChildAddedListener (listener for "users" node) but I am 100% sure I am doing it wrong - among other things because I never know when all the data has been loaded.

Database Structure:

  • Users (NODE)
    • User uid (NODE)
      • username (string)
      • avatar (string)
      • firstname (string)
      • lastname (string)
      • followers (NODE) <- How to get data from this node without making new OnChildListener
      • albums (NODE) <- Same as "followers"

enter image description here

The way I tried to do it

FirebaseDatabase database;
        DatabaseReference userReference;
        DatabaseReference userFollowersReference;

        String loggedUserUid = "uid"; // Logged User UID

        database = FirebaseDatabase.getInstance("url");
        userReference = database.getReference("users").child(loggedUserUid);
        userFollowersReference = database.getReference("users").child(loggedUserUid).child("followers");

        userReference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                String username = snapshot.child("username").getValue(String.class);
                String avatar = snapshot.child("avatar").getValue(String.class);
            }
        });

        userFollowersReference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                List<String> followers = new ArrayList<>();

                followers.add(snapshot.child("followerUid").getValue(String.class));
            }
        });

So - is there a simpler and a better looking way to not clutter the code and to know when all the needed data is loaded?

CodePudding user response:

The snapshot contains everything in the node where you attached the listener. You just need to dig into it to find all the data.

snapshot
    .child("username")
    .child("followers")
    .child("followerUid")
    .getValue(String.class);
  • Related