Android Firebase数据库:删除

时间:2017-05-19 15:24:14

标签: android firebase firebase-realtime-database

我有以下数据库结构:

enter image description here

我需要删除一个孩子(包括键和值),例如第一个,通过知道他的值:xzFD1RahhZYr05nZljIW9BRzvSq1

所以我有

String itemToDelete = "xzFD1RahhZYr05nZljIW9BRzvSq1";
FirebaseDatabase database = FirebaseDatabase.getInstance();
databaseReference deleteRef=database.getReference("richieste").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
deleteRef.orderByValue().equalTo(itemToDelete);
deleteRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        //What to do with .removeValue(); ?
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
}

我不知道如何处理dataSnapshot删除孩子

感谢您的回答

奖金问题:我应该如何处理onCancelled事件?

2 个答案:

答案 0 :(得分:1)

要获取DatabaseReference,您可以致电DataSnapshot.getReF(),然后拨打.removeValue()即可删除该值。

但根据您的情况,您应该迭代DataSnapshot或使用ChildEventListener以确保删除子项而不是richieste/<user_id>下的整个数据。

迭代并删除值:

for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
     childSnapshot.getRef().removeValue();
}

您的代码中还有另一个错误,您应该在附加事件侦听器之前将此行deleteRef.orderByValue().equalTo(itemToDelete);的引用存储到另一个DatabaseReference,或者您可以使用此技巧直接附加侦听器deleteRef.orderByValue().equalTo(itemToDelete).addListenerForSingleValueEvent(...);

对于红利问题,如果读取数据库时出现错误,如网络或权限问题,将调用onCancelled

希望这会有所帮助:)

答案 1 :(得分:0)

威利克的答案涵盖了重要问题。下面的代码实现了它们。

评论更新: Query是Firebase SDK中的一个类。你应该能够导入它:

import com.google.firebase.database.Query;

如果dataSnapshot.exists()为false,则表示数据库中/richieste/$uid没有数据。检查已登录用户的UID是否符合预期,并且数据库中存在该UID的数据。

    String itemToDelete = "xzFD1RahhZYr05nZljIW9BRzvSq1";

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference deleteRef = database.getReference("richieste")
        .child(FirebaseAuth.getInstance().getCurrentUser().getUid());
    // orderByValue() and equalTo() return a query; can't use the original reference
    Query deleteQuery = deleteRef.orderByValue().equalTo(itemToDelete);
    deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                // If the value to delete is not unique, there may be multiple children
                for (DataSnapshot child : dataSnapshot.getChildren()) {
                    // TODO Should also check the result of removeValue()
                    // using a CompletionListener or the returned Task
                    // in case you don't have write access
                    child.getRef().removeValue();
                    Log.d(TAG, "onDataChange: Removed " + child.getKey());
                }
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            // Often get here because of a protection violation;
            // i.e. the security rules are not set to grant read access.
            // One option is to log the failure
            Log.e(TAG, "onCancelled: FAILED " + databaseError.getMessage());
            // Or you can also throw the exception
            throw databaseError.toException();
        }
    });