简体   繁体   中英

How to make a like function in Firebase?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM