I'm trying to update the likes by first reading the current number of likes then later increment the value by 1 however the code doesn't execute in the sequence I expected. How could I immediately update the likes right after getting the datasnaphot value of likes?
Trying to implement likes:
viewHolder.like_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
likes = 0;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("posts");
ref.child( getRef(viewHolder.getAdapterPosition()).getKey()).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//get the current number of likes on the post
likes = dataSnapshot.child("likes").getValue(Integer.class);
Log.w("likes", "likes is " + likes);
// hasRead = true;
Log.w("status", "is "+ hasRead );
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//add a like to exisitng likes
ref.child(getRef(viewHolder.getAdapterPosition()).getKey().toString()).child("likes").setValue(likes+=1);
Log.w("action", "You've liked post with key "+ getRef(viewHolder.getAdapterPosition()).getKey() + " position is "+ viewHolder.getAdapterPosition());
}
});