GavinGD
GavinGD

Reputation: 13

How to find the count of specific values from Firebase in Android Studio?

I have a firebase database consisting of a bunch of cases. I want to loop through all these cases and find the count of Male cases only, male is represented by "M".

Picture of my database.
Picture of my database.

How I am trying to query for this data:

databseCOVIDCases = FirebaseDatabase.getInstance().getReference();

databseCOVIDCases.addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(@NonNull DataSnapshot snapshot) {
       for (DataSnapshot data : snapshot.getChildren()) {
           if (data.child("Sex").getValue(String.class) == "M") {
               numMaleCases++;
           }
       }
   }

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

When I set the text of the text view it shows 0 and then crashes with an out of memory error.

Upvotes: 1

Views: 1846

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598797

Instead of looping through all cases and counting the ones where Sex is M, I'd recommend using a query to only read those nodes. That saves you (and your users) the bandwidth of loading all the nodes where Sex is not M.

In code that'd be:

Query query = databseCOVIDCases.orderByChild("Sex").equalTo("M");
query.addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(@NonNull DataSnapshot snapshot) {
       Log.i("Cases", "M case count: "+snapshot.getChildrenCount());
   }

   @Override
   public void onCancelled(@NonNull DatabaseError error) { 
       throw error.toException(); // Never ignore errors
   }
});

While the above works, a few things to keep in mind:

Upvotes: 1

Related Questions