Reputation: 13
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".
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
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:
Any code that needs the count has to be inside the onDataChange
method or be called from there. Other code may not run when you expect it to run.
For more on this, see getContactsFromFirebase() method return an empty list and Setting Singleton property value in Firebase Listener
Reading all these nodes to only show the count it wasteful. It is much more practical (though unusual if you come from a SQL background) to store the actual count you need in the database, and update it whenever you add/remove a M
node. While your write operations becomes more complex when you do this, your reads become much simpler, cheaper, and more scalable.
For more on this, see How to get size of an element/list in Firebase without get it all? and Is the way the Firebase database quickstart handles counts secure?
Upvotes: 1