-2

this is the database link 1can anybody help me to add a like counter to this.please please it should display the no:of likes and decease it when like is taken back my java code is below

 private void onLikeClicked(View v) {
    boolean isLiked = !btnLike.isSelected();
    final String currentUserKey = User.currentKey();

    DatabaseReference likes = FirebaseDatabase.getInstance().getReference().child(Const.kDataLikeKey);
    DatabaseReference curLike = likes.child(mPostRef.getKey()).child(currentUserKey).child("liked");

    // update Model
    curLike.setValue(isLiked);

    // update UI
    btnLike.setSelected(isLiked);
}

This increment like count but doesn't decrements it i want it to get decremented when clicked back

Kidanu
  • 63
  • 2
  • 9

1 Answers1

2

Your question is not entirely clear but if you are trying to make a functionality like social media post where users can like and unlike a post the this can help.

Data Structure

Post-> postId -> likes -> 1 
              ...

You can divide it in three parts:

  1. To display number of likes for a post , postId & current user, userId1, has liked your post or not

    public void displayNumberOfLikes(String postId, String currentUserId){
        DatabaseReference likesRef = FirebaseDatabase.getInstance().getReference().child('Post').child(postId);
        likesRef.addValueEventListener(new ValueEventListener(){
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if(dataSnapshot.exists()){
                    long numOfLikes = 0;
                    if(dataSnapshot.hasChild("likes")){
                        numOfLikes = dataSnapshot.child("likes").getValue(Long.class);
                    }
    
                    //Populate numOfLikes on post i.e. textView.setText(""+numOfLikes)
                    //This is to check if the user has liked the post or not
                    btnLike.setSelected(dataSnapshot.hasChild(userId));
                }
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
    
            }
        });
    }
    
  2. On Like Clicked

    public void onLikeClicked(View v, String postId, String userId){
        DatabaseReference likesRef = FirebaseDatabase.getInstance().getReference().child('Post').child(postId).child("likes");
        likesRef.addListenerForSingleValueEvent(new ValueEventListener(){
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                long numLikes = 0;
                if(dataSnapshot.exists()){
                    numLikes = dataSnapshot.getValue(Long.class);
                }
                boolean isLiked = btnLike.isSelected();
                if(isLiked){
                   //If already liked then user wants to unlike the post
                   likesRef.set(numLikes-1);
                }else {
                   //If not liked already then user wants to like the post
                   likesRef.set(numLikes+1);
                }
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
    
            }
        });
    }
    

This way you can make your user like and unlike a post and display total number of likes. Hope it helps!

mark922
  • 1,136
  • 2
  • 11
  • 20
  • Thank you sir but this is having a small issue when i unlike it that node is deleted..so say if 2 users have liked it and when one of then press back(unlike) then the whole node is deleted..actually i just want to subtract 1 from the whole like count when the user pres like button again – Kidanu Jun 29 '18 at 15:30
  • Can you add your db structure in the question? It would be helpful if you explain the exact scenario using actual data. – mark922 Jun 29 '18 at 19:44
  • posts -LGEF7JPjhzROruGct_E -image: -likecnt -likecnt: -likes: -time: -user: – Kidanu Jun 30 '18 at 06:18
  • @AryaPrabagar This is not helping. Can put it in a fair image with some explanation – mark922 Jun 30 '18 at 08:41
  • sir i have added a image link – Kidanu Jun 30 '18 at 09:42
  • i have tried the code when i click like/unlike the counting goes to infinity..ie for +1 likes it keeps on counting and never stops – Kidanu Jun 30 '18 at 13:02
  • Sorry I implemented addValueEventListener instead of addListenerForSingleValueEvent. I have corrected the answer. – mark922 Jun 30 '18 at 15:50
  • the code "numLikes = dataSnapshot.getValue(Long.class);" gives me an error so i have changed the code to public void onDataChange(DataSnapshot dataSnapshot) { long numLikes = 0; if(dataSnapshot.exists()) { boolean isLiked = !btnLike.isSelected(); if (isLiked) { //If already liked then user wants to unlike the post likes.setValue(numLikes - 1); but i cannot get the value from firebase databse – Kidanu Jul 03 '18 at 14:13
  • java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference at me.android.prj.frdes.adapters.StoryViewHolder$2.onDataChange(StoryViewHolder.java:372) – Kidanu Jul 05 '18 at 07:28
  • Sorry for the late reply. I have added the null pointer check for dataSnapshot in function displayNumberOfLikes. – mark922 Jul 12 '18 at 06:32