How do I achieve this in Java, I set up my database in the format below, under Notification I have a child set up with a random key generated by Firebase and then I have other children under as below.
Notification ----
dhsj37egshehhdeh----
name - john
userid - 939jjddehhd
status - unread
347747dhhshhdeh3----
name - doe
userid - 956jj53hdhhd
status - read
I am trying to get children count where status is equal to unread.
I tried to use reference.child("Notification").orderbyChild("status").equalTo("unread"){ then i get children count.
But I am not getting the children count, as I assume first have to reference the child key then how do I get the children count?
CodePudding user response:
Since you say you're using the Java, the simplest way to achieve that would be:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference notificationRef = db.child("NotificationV2");
Query queryByStatus = notificationRef.orderByChild("unread").equalTo(true);
queryByStatus.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
long count = snapshot.getChildrenCount();
Log.d("TAG", "count: " count);
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be the exact number of children your query returns. So please note that the key to solving this problem is the use of the DataSnapshot#getChildrenCount() method.
Edit:
If you have changed the name of the field from "status" to "unread" and the value to be boolean, and the name Notification
to NotificationV2
then please check my updated code. Besides that, we cannot see the other 5 elements. However, if all the other elements exist at the exact same level, then the above code should definitely work.