您好,如何使用Java删除fire_base数据库中的节点? 我已经尝试过这种方法,但是没有用。 该图显示了节点结构 the node struct
private void deleteTask (final String userName){
final DatabaseReference reference = FirebaseDatabase.getInstance().getReference("All_USER");
reference.orderByChild("userName").equalTo(userName).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds :dataSnapshot.getChildren()){
String userName = (String) ds.child("userName").getValue();
reference.child(userName).setValue(null);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
答案 0 :(得分:0)
尝试以下代码:
private void deleteTask (final String userName){
final DatabaseReference reference = FirebaseDatabase.getInstance().getReference("All_USER");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds :dataSnapshot.getChildren()){
ds.getRef().orderByChild("userName").equalTo(userName).removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
答案 1 :(得分:0)
此代码对我有用
private void deleteTask (final String userName){
final DatabaseReference reference = FirebaseDatabase.getInstance().getReference("All_USER");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds :dataSnapshot.getChildren()){
if(ds.child("NewUser").child("userName").getValue(String.class).equals(userName)){
ds.child("NewUser").child("userName").getRef().removeValue();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
答案 2 :(得分:0)
您可以像这样更改代码:
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (snapshot in dataSnapshot.children) {
snapshot.reference.removeValue()
}
}
}