willy
willy

Reputation: 101

Get children count of a node inside another node in Firebase

I want the number of children under a subject ID that has a value of "4112021yes" in the "weeksearch" key as shown in the attached image. I do not want to focus on the userId because there can be several userids under the same subject id. I have tried doing this

DatabaseReference reference2 = FirebaseDatabase.getInstance().getReference("attendance").child(subjectId);
            Query query2 = reference2.orderByChild("weeksearch").equalTo(week+"yes");
            query2.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    long numberOfUsers = snapshot.getChildrenCount();
                    noOfAbsentStudents = (int) numberOfUsers;
                     
                }

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

                }
            });

But was not successful. Any suggestions on how I can get that children count?

I want the number of children under the subject id that has a value of "4112021yes" in the "weeksearch" key

Upvotes: 0

Views: 147

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138834

To be able to get the count of all children who have the weeksearch field set to 4112021yes, please use the following query:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = db.child("attendance").child(subjectId).child(uid);
                                                                          👆
Query queryByWeekSearch = uidRef.orderByChild("weeksearch").equalTo(week + "yes");
queryByWeekSearch.addValueEventListener(/* ... /*);

Remember that you need to add all nodes inside your reference, including the UID of the users.

Edit:

What I want is all the nodes under the subjectId.

That's not possible with your actual database structure. The queries in the Realtime Database work on a flat list of nodes, where the value on which you want to perform the filter must be at a fixed path under each direct child node. That being said, you should use a simpler database schema that can allow you to perform the desired query. The simplest I can think of would be to add the UID as property of each child:

Firebase-root
  |
  --- attendance
        |
        --- $subjectId
              |
              --- weeksearch: "4112021yes"
              |
              --- uid: "8IMf...ndA3" 👈

Case in which you can leave your actual code untouched.

Upvotes: 2

Related Questions