2
votes

I am trying to query nodes from Firebase realtime database to my firebase recycler adapter where "userId" child value is found in a String ArrayList.

So I have a node called "Follows" where every users follows inside the app are stored. It looks like this. Then I have node called "Posts" where every post by any user is stored. Every indivitual post have multiple childs containing info about the post and one of them is child called "userId". Looking like this.

I have retrieved each follows user id like this:

final ArrayList<String> usersFollows = new ArrayList<>();
                    DatabaseReference usersFollowsRef = FirebaseDatabase.getInstance().getReference().
                            child("Follows").child(currentUserId);

                    usersFollowsRef.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot)
                        {
                            if(dataSnapshot.exists())
                            {
                                for(DataSnapshot snapshot : dataSnapshot.getChildren())
                                {
                                    String followsKey = snapshot.getKey();
                                    usersFollows.add(followsKey);
                                }
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

Now I would have to make a query which retrieves every post that has "userId" value found in this "usersFollows" ArrayList but I don't really know how to achieve my goal. For example I cant write Query query = postsReference.orderByChild("userId").equalTo(usersFollows); because you cant pass an array inside equalTo() statement.

Am I on the right path or is there a more convinient way of doing this?

1

1 Answers

1
votes

Unfortunately, firebase doesn't allow multiple equalTo(). I suggest you to review your db in that way: Posts -> Date -> UserId -> PostId and adding a .read rules that check if the UserId in Follow list is true:

Posts: {
  "$date" :{
     "$userId": {
                ".read": "root.child(follows).child(auth.uid).child($userId).val() === true"
                }
           }
     }

In this way you can obtain the post by date and automatically reduce the visibility scope.

EDIT:

You can maintain your actual schema adding this rule:

 Posts: {
  "$post":{
        ".read": "root.child(follows).child(auth.uid).child(data.child(userId)).val() === true"
        }
     }