Reputation: 35
I want to obtain number of elements in Firebase Realtime DB.
I can get number of childs but not number of elements.
For example:
https://i.hizliresim.com/Lb46ao.png
As you see number of childs 3, my code returns 3 but I want to count all elements not childs.
root.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
totalSize = (int) dataSnapshot.getChildrenCount(); //It gives 3,
//not number of elements. I want to obtain number of elements. Number of elements 1204 for now.
}
@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: 1
Views: 1498
Reputation: 598797
You're currently counting the number of properties under each child, so that gives 3: msg
, name
, time
.
To count the number of children, you'll want to use a ValueEventListener
:
root.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
totalSize = (int) dataSnapshot.getChildrenCount();
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
Upvotes: 3