Android-如何使用Firebase在帖子中显示喜欢数

时间:2018-07-07 14:37:25

标签: android firebase count facebook-like

我想打印特定帖子的总赞数。但是在此代码中我出现了一个错误long numOfLikes = dataSnapshot.child("likes").getValue(Long.class);,错误是尝试调用虚拟方法'long java.lang.Long。在空对象引用上使用longValue()” enter image description here

我的代码是

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

    DatabaseReference likes = FirebaseDatabase.getInstance().getReference().child(kDataLikeKey);
    DatabaseReference curLike = likes.child(mPostRef.getKey()).child(currentUserKey).child("likes");
    likes.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        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);
                }
            } else {

                //If not liked already then user wants to like the post
                likes.setValue(numLikes + 1);
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    // update Model
    curLike.setValue(isLiked);

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

}
public void displayNumberOfLikes(){
    boolean isLiked = !btnLike.isSelected();
    final String currentUserKey = User.currentKey();

    DatabaseReference likes = FirebaseDatabase.getInstance().getReference().child(kDataLikeKey);
    DatabaseReference curLike = likes.child(mPostRef.getKey()).child(currentUserKey).child("likes");
    likes.addValueEventListener(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists()){
                long numOfLikes = dataSnapshot.child("likes").getValue(Long.class);
                mlikecnt.setText(""+numOfLikes);
                //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(currentUserKey));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

1 个答案:

答案 0 :(得分:0)

DatabaseReference likes = FirebaseDatabase.getInstance().getReference().child("posts").child("KEY_WHATEVER_YOU_ARE_USING").child("likes");
likes.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
           long numOfLikes = dataSnapshot.getValue(Long.class);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });