COUNT AT FIREBASE

Asked

Viewed 507 times

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 of occurrences created (ALL of all users) and total per user, but, I do not know how to perform Count in the firebase database.

The Count I wanted to make is for the bank below. Database firebase

Can anyone help me? Hugs.

1 answer

1

Below is an example of code to 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) {}
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.