0

I need to count all the children that are in my Firebase database.

This is the Firebase structure:

Level 1 - CHILD1 - - subchild1 - - subchild2 - CHILD2 - - subchild 1

How can I count the CHILDs from level 1? (In this example it would need to return 2...)

KENdi
  • 7,576
  • 2
  • 16
  • 31
pipafria
  • 102
  • 1
  • 2
  • 9

4 Answers4

1

Query the first level and then in your SnapShot, use : getChildrenCount().

So the query will be something like this:

myRef.child("level1").child("subchild1"). // Your listener after

Check this link.

And here.

ʍѳђઽ૯ท
  • 16,646
  • 7
  • 53
  • 108
0
DatabaseReference mDatabaseRef = FirebaseDatabase.getInstance().getReference();
mDatabaseRef.child("level1").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                   long count= dataSnapshot.getChildrenCount();

                }  
             });
SABANTO
  • 1,316
  • 9
  • 24
0

Try This

FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference ref = db.getReference();

ref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    Log.e(dataSnapshot.getKey(),dataSnapshot.getChildrenCount() + "");
}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});
Sniffer
  • 1,495
  • 2
  • 14
  • 30
0

This code will help you .

(int)dataSnapshot.getChildrenCount()
Abdullah alkış
  • 325
  • 4
  • 13