To count the number of children that a reference has, you'll have to add a ValueEventListener
and then call dataSnapshot.getChildrenCount()
inside the onDataChange(DataSnapshot dataSnapshot)
method.
However, instead of this, what you can do is that you can have a separate node in your database that contains the value (integer) of the number of children of the node whose children you need to keep count of. You could name the node something like Reference-ChildrenNumber
. You can update this node whenever data is inserted or deleted from the reference that you need to keep track of. Then, when you need this data, instead of downloading the entire contents of the reference node, you can just read this node and get the count.
I would recommend you to make these changes in a transaction
so that concurrent writes do not lead to incorrect data. Also, you can do this from the client, but I would recommend you to use Cloud Functions for Firebase. An example of exactly what you're looking for using Cloud Functions is this.