Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Query and Ref Firebase Database Android

My firebase database looks like this:

database

From this query

String currentUserID = FirebaseAuth
                            .getInstace()
                            .getCurrentUser()
                            .getUid();

DatabaseReference favorsRef = FirebaseDatabase
                                        .getInstance()
                                        .getReference()
                                        .child("favors");
Query myChatsQuery = favorsRef
                        .orderByChild("uid")
                        .equalTo(currentUserID);

I need to create other query to get just the tuples from myChatsQuery who has the child called "messages". If the tuple doesn't have the child "messages", I don't want to insert it in my new query.

So, How I can create a query from other query?

Help me please,

Thanks in advance.

like image 609
esterrrsinH Avatar asked Mar 11 '26 00:03

esterrrsinH


1 Answers

Unfortunately, orderByChild() does not work on multiple same fields at once, so you may have to do the job in two steps.

First you can run an orderByChild() query looking for the currentUserId and then add all those that match to an ArrayList and then run orderByChild() in those found uids for messages.

This looks something like this, in code:

reference.orderByChild("uid").equalTo(currentUserId).addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            if(dataSnapshot.exists())
                              array.add(dataSnapshot.getValue(String.class);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                  )};

This code above adds uids matching currentUserId to the ArrayList array.

databaseReference.child(array.get(0)).addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                           if(dataSnapshot.child("messages").exists())
                           // do your thing

                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }

                    )};    

You can also just use a for loop to go through all the values in the array.

like image 114
PradyumanDixit Avatar answered Mar 12 '26 15:03

PradyumanDixit