0

I'd like to know how can I count the number of snapshots that a Reference has inside of it in Firebase, so the next example I could get a value of 5.

 

    -TheReference
        -KoiWSAUZvT4RlBui4TY
        -KojK1uz0go1beOKPVtP
        -KooR3HzDcrGPq068t7T
        -KowcGAukSnUy5hjTUf5
        -KowtzW0SQYvbX87FAXN

I just want to count once the app starts and not in every database changes, so I'm not contemplating to use ValueEventListener or SingleValueEventListener over the reference.

Is that possible?

I'l Follio
  • 573
  • 1
  • 7
  • 19

2 Answers2

0

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.

Rohan Stark
  • 2,346
  • 9
  • 16
  • That'd be nice but the data request in that new Reference will be the same, consulting with addValueEventListener or addSingleValueEventListener isn't it? I'm looking for something to consult just once. – I'l Follio Jul 13 '17 at 21:13
  • How can you read data from a database without accessing the database? – Rohan Stark Jul 13 '17 at 21:28
  • And `addSingleValueEventListener` retrieves data just once. No subsequent changes to the node will be downloaded. Hence the "single". – Rohan Stark Jul 13 '17 at 21:39
0
datasnapshot.getChildrenCount()

According to https://firebase.google.com/docs/reference/android/com/google/firebase/database/DataSnapshot