Reputation: 79
The structure in which I store the likes of a post is as shown below :
This is how I store the information of a post:
UID is of the user ID of the user who posted the post of course.
I want to get the total number of likes that a particular user with UID got on all of his posts
For example:
A user with uid: Avvj7v9v has two posts with 4 and 2 likes, respectively. So, the total number of likes that all of his posts got is 6.
I want a way to get that number of likes which is 6 in this example.
Upvotes: 2
Views: 815
Reputation: 4311
Go to databaseReference.child("Posts")
and loop through all the posts, find those whose uid
child matches the desired user, and keep that subset of post IDs, say in an ArrayList, postsOfTheUser
.
Next, go to databaseReference.child("Likes")
and loop through all the likes. Ignore all children whose post ID is not in postsOfTheUser
, but those whose post ID is in postsOfTheUser
, proceed to sum the likes, using getChildrenCount()
for each of the posts.
Upvotes: 1
Reputation: 2377
You can do something like this.
databaseReference.child("Likes").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
long sum = 0;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
long size = snapshot.child(UUID).getChildrenCount();
sum += size;
textView.setText("Total Likes for this User: " + sum);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Upvotes: 0