Dima Bokov
Dima Bokov

Reputation: 101

Retrieve count data from Firebase database

I have the following database. What I need is to get the total count of comments per post when posting UID equal to current_user_uid.

Any suggestion on how to do this?

Firebase database example

Upvotes: 1

Views: 2140

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 139019

To solve this, please use the following code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Posts").orderByChild("uid").equalTo(current_user_uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            long count = ds.child("comments").getChildrenCount();
            Log.d("TAG", "Count: " + count);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage());
    }
};
query.addListenerForSingleValueEvent(valueEventListener);

Upvotes: 1

Related Questions