0

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?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Oana
  • 19
  • 5

1 Answers1

1

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Ok, I'll try to implement the way you said, but one more questions is if it is possible to delete the collection after you close the app. I use the collection as a "shopping cart" (to say so) and everytime I run the app again, I want this cart to be empty, so in order to do that I should delete what was previosly in the cart. – Oana Aug 29 '22 at 11:08
  • Or, you should consider using [Cloud Functions for Firebase](https://firebase.google.com/docs/functions). – Alex Mamo Aug 29 '22 at 11:20