0

Let's say I have a Firebase Realtime database structure where there are user nodes and each user node has post nodes that only contain post ids. Then there are also separate post nodes where the actual posts reside (flat data structuring). The structure is described in detail in this answer.

Now if I can get the ids of the posts of each user by attaching a listener to that user's posts node, how can I retrieve the posts themselves (full information from a post node)? I know there aren't any queries where one can pass a bunch of keys and get the associated records. Should I just attach a listener to each post node I am interested in? I'm currently afraid there might be some serious performance issues, because the number of posts is practically unlimited.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Salivan
  • 1,876
  • 7
  • 26
  • 45

1 Answers1

1

Using the exact database structure from this post, to solve your problem, you need to query your database twice. Once to get the post ids of the particular user you need and second to get the posts it self. To achieve this, please use the following code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child("users").child(uid).child("posts");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String postId = ds.getKey();

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

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

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
postsRef.addListenerForSingleValueEvent(valueEventListener);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • So yeah, that's what I've said: I should attach a listener to each post node, except that in your example that's a single value event listener, so I guess that must be way more efficient than constantly listening to events on each post node. Thanks for confirmation and clarification! – Salivan Mar 31 '18 at 13:50