Lionlollipop
Lionlollipop

Reputation: 123

Delete a document from Firestore

I am trying to delete a document from a collection called "photo" but it doesn't work, there is no OnFailureException message as OnSuccess Toast is shown but the document still remain in the Firestore :(

Structure of the firestore: enter image description here

This is the codes I use to delete the document:

        Photo photo = (Photo) getIntent().getSerializableExtra("photo");

        FirebaseFirestore db = FirebaseFirestore.getInstance();

        String userId = mAuth.getCurrentUser().getUid();

        CollectionReference photoRef = db.collection("main").document(userId).collection("photo");

DocumentReference document = photoRef.document(photo.getId());
                    String currentDocumentID = document.getId();
                    photoRef.document(currentDocumentID).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Toast.makeText(ViewPhotoActivity.this, "Entry Deleted", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(ViewPhotoActivity.this, PhotoActivity.class));
                            finish();
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(ViewPhotoActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });

Upvotes: 0

Views: 250

Answers (2)

Lionlollipop
Lionlollipop

Reputation: 123

I am sure there are several ways to do this which includes the answer I received above, the getID method is a little confusing to me as it doesn't work sometimes or give me a null exception, so I changed my code and use a simpler way, which is to create a unique ID for each document when they are being created, then set the document Id with that unique ID so I could retrieve them easily, for this case, I created the ID by combining the title and 6 random digits.

When creating the document, I added a unique ID field for each document:

//set a unique ID for each photo
                String randomSixNumbers = getRandomNumberString();
                String photoId = (title.toLowerCase() + randomSixNumbers).replace(" ", "").trim();

//set ID to new object 
              Photo photo = new Photo(photoId, title, photoDescription, filePath, datePhoto);

//add object to firestore and set document ID as the uniqueID instead of the default auto-generated documentID                 
              photoRef.document(photoId).set(photo).addOnSuccessListener(...

delete the document using the unique ID:

photoRef.document(photo.getId()).delete().addOnSuccessListener(...

For now, this process seems okay, though I am not sure if it is a good practice or not? If not, could someone point out the downside/fault of this method?

And I noticed that I have to use intent to get the data passing from last activity to get the object data in current activity.

Upvotes: 0

AsifM
AsifM

Reputation: 699

I am writing the answer from speculation as there is not enough information as to how you are creating the document.

DocumentReference document = photoRef.document(photo.getId());

In the above line you are creating a reference to a document with photo id. Looking at the document data it seems the photo id is not same as the document id.

Therefore when you create the above reference- you are not referring to the existing document with id="2BMG3..." rather a NEW document with id="jYBPX..."

String currentDocumentID = document.getId();
photoRef.document(currentDocumentID).delete()

How you can fix it depends on how you want to save/create the documents. One way could be to create the documents in photo collection with id= photo id in the first place.

For example, when creating, you could create the document reference as following:

CollectionReference photoRef = db.collection("main")
                                .document(userId)
                                .collection("photo")
                                .document(photo.getId());

And then set the data as:

photoRef.set(photo);

That'd set the data to a document you have created with id=photo id.

These examples can be improved if you show how you're adding documents to photo collection now. If you've been using .colection('photo').add() or .collection.document().set(photo) then the created document would have an auto-generated id different from the photo id.

Upvotes: 2

Related Questions