0

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());
  }
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Nick.K
  • 320
  • 6
  • 11

1 Answers1

1

To solve this, you definitely need to use Firebase Transactions.

When working with data that could be corrupted by concurrent modifications, such as incremental counters, you can use a transaction operation.

To achieve this, please use my answer from this post in which I have explained how you can increment a value in Firebase Realtime database and how you can read it back.

You can also tale a look at this post for a better understanding regarding of asynchronous methods.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193