我需要在单击按钮时从Firebase中删除一个子节点,但是当我使用.RemoveValue()时,它会删除所有的子节点,而不仅仅是一个。
LeaderClass leader = new LeaderClass((uploadCurrent.getName()).trim(),
(uploadCurrent.getCategory()).trim(),(Integer.toString(mCountLikes )));
mDatabaseLike.removeValue();
完整代码如下:
//Count Likes functionality
mDatabaseRef.child((uploadCurrent.getName())).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
//Counting likes in 'Likes' database by counting children
mCountLikes = (int) dataSnapshot.getChildrenCount();
holder.mCountbtn.setText(Integer.toString(mCountLikes ) + " Likes" );
LeaderClass leader = new LeaderClass((uploadCurrent.getName()).trim(),
(uploadCurrent.getCategory()).trim(),(Integer.toString(mCountLikes )));
mDatabaseLike.push().setValue(leader);
}
else{
holder.mCountbtn.setText("0 Likes");
LeaderClass leader = new LeaderClass((uploadCurrent.getName()).trim(),
(uploadCurrent.getCategory()).trim(),(Integer.toString(mCountLikes )));
mDatabaseLike.removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
这是我的firebase结构:
CountLikes: {
"-LXBQRbkiL3fZUnRedrB": {
category: "Technology"
name: "Project 467"
vote: "1"
}
答案 0 :(得分:0)
当您在removeValue
上调用DatabaseReference
时,Firebase会删除该引用上的所有数据。看来您的mDatabaseLike
指向CountLikes
,因此调用mDatabaseLike.removeValue()
会删除该位置下的所有数据。
要删除单个子节点,您需要知道要删除的类似键,即您共享的JSON中的-LXBQRbkiL3fZUnRedrB
。
当您知道这一点时,只需删除一个子节点就很简单:
mDatabaseLike.child("-LXBQRbkiL3fZUnRedrB").removeValue();