Reputation: 102
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...)
Upvotes: 0
Views: 12618
Reputation: 333
This code will help you .
(int)dataSnapshot.getChildrenCount()
Upvotes: 0
Reputation: 101
DatabaseReference mDatabaseRef = FirebaseDatabase.getInstance().getReference();
mDatabaseRef.child("level1").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long count= dataSnapshot.getChildrenCount();
}
});
Upvotes: 0
Reputation: 1595
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) {
}
});
Upvotes: 0
Reputation: 16976
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.
Upvotes: 1