Reputation: 1046
I can't get done the count of likes. The users can like a post and I want Firebase count how many likes post gets from users.
My code:
viewHolder.mThumb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mProcessLikes = true;
mDatabaseLikes.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLikes){
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){ mDatabaseLikes.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessLikes = false;
} else {mDatabaseLikes.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue("like");
mProcessLikes = false;
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
}
});
What code should I add in the code above to achieve the result is showed on attached image?
Upvotes: 1
Views: 1796
Reputation: 7892
Remove the count
field from you table. If I understand correctly.. When an object is being liked, some user id is being added. This works and is sufficient. Query your like count as followed:
databaseRef.child("Likes").child(*key*).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange (DataSnapshot dataSnapshot) {
dataSnapshot.getChildrenCount(); <- like count
}
@Override
public void onCancelled (DatabaseError databaseError) {
}
});
Upvotes: 1
Reputation: 1925
You should read about Save data as transactions from the Firebase Documentation,
For example :
private void onStarClicked(DatabaseReference postRef) {
postRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Post p = mutableData.getValue(Post.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.stars.containsKey(getUid())) {
// Unstar the post and remove self from stars
p.starCount = p.starCount - 1;
p.stars.remove(getUid());
} else {
// Star the post and add self to stars
p.starCount = p.starCount + 1;
p.stars.put(getUid(), true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "postTransaction:onComplete:" + databaseError);
}
});
}
Full example here
Upvotes: 0