Home > Software design >  Delete documents of cloud firestore collection after I close the app
Delete documents of cloud firestore collection after I close the app

Time:08-30

So I have a collection in Cloud Firestore which I populate by clicking some buttons in my application. Once I close the app, I want the collection to be empty. Is there any way I can do that? I tried to implement onStop() method, but it does nothing.

protected void onStop() {
    super.onStop();
    db.collection("AddPlaces").document()
            .delete()
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.d("SUCCES", "DocumentSnapshot successfully deleted!");
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w("FAILURE", "Error deleting document", e);
                }
            });
}

Any ideas if I can achieve that?

CodePudding user response:

An empty collection means a collection with no documents. If you want to delete all documents in a collection, I recommend you see my answer in the following post:

Why your code is not working? Is because of the following line of code:

db.collection("AddPlaces").document()

Which basically generates a document with a random ID, and nothing more. So when you call delete(), you're trying to delete a single document and not all documents in the collection, hence that behavior.

One more thing to note is that if you delete all documents in the collection, that collection will not exist anymore. It will exist again when you'll write a new document in it.

  • Related