如何从firebase实时数据库中删除?

时间:2022-01-13 13:22:35

I am using Firebase realtime database in Android app, and have data like this: 如何从firebase实时数据库中删除?

我在Android应用中使用Firebase实时数据库,并且拥有如下数据:

How can i delete the record "Apple" (marked in picture)?

如何删除记录“Apple”(标记在图片中)?

According to the docs, to remove an item you call removeValue() on the reference. But to get the reference i require the child id. Because its a random generated id (-KISNx87aYigsH3ILp0D), how to delete it?

根据文档,删除一个项目,你在引用上调用removeValue()。但要获得引用我需要子ID。因为它是一个随机生成的id(-KISNx87aYigsH3ILp0D),如何删除呢?

2 个解决方案

#1


43  

If you don't know the key of the items to remove, you will first need to query the database to determine those keys:

如果您不知道要删除的项的键,则首先需要查询数据库以确定这些键:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query applesQuery = ref.child("firebase-test").orderByChild("title").equalTo("Apple");

applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) {
            appleSnapshot.getRef().removeValue();
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.e(TAG, "onCancelled", databaseError.toException());
    }
});

#2


2  

Depending on how and why you are deleting the data you can use these:

根据您删除数据的方式和原因,您可以使用以下内容:

// Could store the push key or get it after push
String newPostKey = yourDatabase.child('firebase-test').push({
    something:something
}).key();

// Depends how you get to here
howYouGotHereId.parent().setValue(null);

Firebase Save Data 3.0

Firebase保存数据3.0

#1


43  

If you don't know the key of the items to remove, you will first need to query the database to determine those keys:

如果您不知道要删除的项的键,则首先需要查询数据库以确定这些键:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query applesQuery = ref.child("firebase-test").orderByChild("title").equalTo("Apple");

applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) {
            appleSnapshot.getRef().removeValue();
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.e(TAG, "onCancelled", databaseError.toException());
    }
});

#2


2  

Depending on how and why you are deleting the data you can use these:

根据您删除数据的方式和原因,您可以使用以下内容:

// Could store the push key or get it after push
String newPostKey = yourDatabase.child('firebase-test').push({
    something:something
}).key();

// Depends how you get to here
howYouGotHereId.parent().setValue(null);

Firebase Save Data 3.0

Firebase保存数据3.0