1

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
GavinGD
  • 13
  • 7

1 Answers1

1

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:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807