0

I am trying to retrieve a list of friends for a user so I can display them in a list view. The friends and user info is structured like this in my firebase database:

enter image description here

enter image description here

So basically, I want to take the user ids listed in the friends part and query my users data to get all the info under every node that is in that set of user ids. How can I achieve this using the android firebase database sdk querying? I would like to be able to retrieve all the users in a single database query.

Thanks.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Jacob Stinson
  • 181
  • 1
  • 16
  • There is no Firebase equivalent for SQL's `SELECT * FROM users WHERE id IN (1,2,3)`. See https://stackoverflow.com/questions/29560088/firebase-equivalent-to-sql-where-in. But the performance implications of doing multiple loads are not nearly as bad as you may think. See http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786 – Frank van Puffelen Dec 04 '17 at 04:47

1 Answers1

2

You cannot get that data in single query, you need to query your database twice. This is a common practice when it comes to Firebase. Assuming that friends and users nodes are direct childs of your Firebase root, to achieve this, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference friendIdRef = rootRef.child("friends").child(friendId)
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String key = ds.getKey();

            DatabaseReference usersRef = rootRef.child("users").child(key);
            ValueEventListener eventListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
                        String username = dSnapshot.child("username").getValue(String.class);
                        Log.d("TAG", username);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {}
            };
            usersRef.addListenerForSingleValueEvent(eventListener);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
friendIdRef.addListenerForSingleValueEvent(valueEventListener);

It will print all user names of those particular users. One more thing to note, is that you don't need to add in your database those friends that have the value of false, only those with the value of true.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193