It only counts the red mark, what I needed is the black mark.
How do I retrieve the data?
String userID = FirebaseAuth.getInstance().getUid();
public static final String TAG = "TAG";
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("babylist").child(userID);
db.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int counter = (int) dataSnapshot.getChildrenCount();
String userCounter = String.valueOf(counter);
babycount.setText(userCounter);
usercount.setText(userCounter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
CodePudding user response:
it only counts the red mark, what I needed is the black mark
That's the expected behavior since you are looping through the data only once. Calling .child(userID)
will always count the number of children under the user ID node. To count all the children of all users, you need to add a nested loop like in the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference babylistRef = db.child("babylist");
babylistRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
int userCounter = 0;
for (DataSnapshot userSnapshot : task.getResult().getChildren()) {
for (DataSnapshot snapshot : userSnapshot.getChildren()) {
userCounter ;
}
}
babycount.setText(userCounter);
usercount.setText(userCounter);
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});