COUNT on firebase

1

Hello,

Is it possible to do COUNT (record count) in the firebae database? Because I would like to return in my app the total number of occurrences created (TODAS of all users) and total per user, but, I do not know how to do count in the firebase database.

The count I wanted to do is for the bank below.

Can anyone help me? Hugs.

    
asked by anonymous 14.10.2017 / 15:45

1 answer

1

Here is an example code to do this count by rank and total:

final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("usuario");

ref.addListenerForSingleValueEvent(new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot) {
        HashMap<String, Integer> map = new HashMap<>();
        int mTotal=0;

        for (DataSnapshot snap : dataSnapshot.getChildren()) {
            String mUserKey = snap.getKey();
            if (snap.child("ocorrencia").exists()) {
                map.put(mUserKey, (int) snap.child("ocorrencia").getChildrenCount());
            }
        }

        for (Map.Entry<String,Integer> entry : map.entrySet()) {
            System.out.printf("%s -> %s%n", entry.getKey(), entry.getValue());
            mTotal = mTotal + entry.getValue();
        }
        System.out.printf("Somatória total de ocorrências: %s%n", mTotal);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
});
    
03.11.2017 / 02:44