如何添加像计数器Android Studio Firebase

时间:2018-06-28 17:06:34

标签: android firebase firebase-realtime-database

this is the database link 1,有人可以帮我添加一个类似的计数器吗?请 它应该显示no:of点赞并在点赞被收回时降低 我的Java代码在

下面
length

这种增加类似于计数,但不减少,我希望它在单击时会减少

1 个答案:

答案 0 :(得分:0)

您的问题尚不完全清楚,但是,如果您尝试创建社交媒体帖子这样的功能,用户可以喜欢它,而与帖子不同,这可以提供帮助。

数据结构

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

您可以将其分为三个部分:

  1. 要显示帖子的点赞次数postId和当前用户userId1是否喜欢您的帖子

    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. 像点击一样点击

    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) {
    
            }
        });
    }
    

这样,您可以使用户喜欢和不喜欢帖子,并显示喜欢的总数。 希望对您有帮助!