我是初学者,我正在开发一个 android 项目,用户喜欢管理员为他们发布的帖子。当用户点击喜欢按钮时,喜欢的内容会更新到 firebase。问题是即使用户喜欢或不喜欢该帖子,喜欢的数量仍在增加。请调查一下。
笔记:
Log.d(TAG, "Liked onDataChange: "+isLiked);
无论我们喜欢还是不喜欢shinebutton,都返回false。Shinebutton 是一个图书馆。
链接到它的 GitHub: Shinebutton Github
onLike 方法:
@Override
public void onLike(View v, int position) {
UploadImage selectedItem = mUploads.get(position);
String selectedKey = selectedItem.getKey();
final ShineButton shineButton = new ShineButton(Objects.requireNonNull(getActivity()));
shineButton.setBtnFillColor(RED);
shineButton.setShapeResource(R.raw.heart);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100,100);
shineButton.setLayoutParams(layoutParams);
final DatabaseReference likesRef = FirebaseDatabase.getInstance().getReference().child("ImageUploads").child(selectedKey).child("likes");
likesRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(@NotNull DataSnapshot dataSnapshot) {
long numLikes = 0;
if(dataSnapshot.exists()){
numLikes = dataSnapshot.getValue(Long.class);
}
boolean isLiked = shineButton.isSelected();
Log.d(TAG, "Liked onDataChange: "+isLiked);
if(isLiked){
//If already liked then user wants to unlike the post
likesRef.setValue(numLikes-1);
}else {
//If not liked already then user wants to like the post
likesRef.setValue(numLikes+1);
shineButton.setEnabled(false);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
ShineButton like = layout.findViewById(R.id.like_feed);
System.out.println(RED);
like.setBackground(getResources().getDrawable(R.drawable.like_feed_bg));
}
修改代码后:现在,即使我们喜欢或不喜欢,计数也不会增加或减少。
类似方法:
public void onLike(View v, int position) {
UploadImage selectedItem = mUploads.get(position);
String selectedKey = selectedItem.getKey();
final ShineButton shineButton = new ShineButton(Objects.requireNonNull(getActivity()));
shineButton.setBtnFillColor(RED);
shineButton.setShapeResource(R.raw.heart);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100,100);
shineButton.setLayoutParams(layoutParams);
final DatabaseReference likesRef = FirebaseDatabase.getInstance().getReference().child("ImageUploads").child(selectedKey).child("likes");
likesRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(@NotNull final DataSnapshot dataSnapshot) {
long numLikes = 0;
if(dataSnapshot.exists()){
numLikes = dataSnapshot.getValue(Long.class);
}
final long finalNumLikes = numLikes;
shineButton.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(View view, boolean checked) {
if (checked){
likesRef.setValue(finalNumLikes-1);
}
else{
likesRef.setValue(finalNumLikes+1);
}
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
ShineButton like = layout.findViewById(R.id.like_feed);
System.out.println(RED);
like.setBackground(getResources().getDrawable(R.drawable.like_feed_bg));
}