0

There is an application in it posts. Likes, done as follows:

postReference = firebaseDatabase.getInstance().getReference().child("Posts");   
holder.likeBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final DatabaseReference likeReference = postReference.child(listUserId).child("Likes");
        likeReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (!dataSnapshot.hasChild(currentUserId)) {
                    likeReference.child(currentUserId).removeValue();
                } else {
                    likeReference.child(currentUserId).setValue("Like");
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });
    }
}

The problem is that after pressing the button, the record in the database begins to be added and deleted without stopping. How to fix it? My DB:

my_database

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Binary
  • 421
  • 4
  • 12

1 Answers1

0

To solve this, please change the following line of code:

likeReference.addValueEventListener(new ValueEventListener() {}

to

likeReference.addListenerForSingleValueEvent(new ValueEventListener() {}

See addListenerForSingleValueEvent official documentation:

Add a listener for a single change in the data at this location.

Using addValueEventListener it means that you are keeping the listener active all the time. To remove the listener, please see my answer from this post.

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