Badri Paudel
Badri Paudel

Reputation: 1630

How to delete Item from firestore in android with auto-generated document ID

I have a Firestore database with the following structure in a hierarchical form:

collection("notes") > document(currentUserId) > collection("mynotes") > document(auto-generated-key) > items...

I have added data to the Firestore as follows :

   mAuth = FirebaseAuth.getInstance();
   database = FirebaseFirestore.getInstance();
  
   //here scheduleModel is a model class with constructor(String, boolean, String) with getters and 
   //setters for three of them 
   scheduleNoteModel = new ScheduleNote(noteTitle, isImp, strDate);

I have added the note item like this.

database.collection("notes").document(mAuth.getUid())
            .collection("mynotes")
            .document() //generated id automatically...
            .set(scheduleNoteModel)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Toast.makeText(getContext(), "data added ...", Toast.LENGTH_SHORT).show();
                    etNoteTitle.setText("");
                    //dismiss (hide) the bottom sheet after adding item
                    BottomSheetScheduleFragment.this.dismiss();

                    //refresh the fragment
                }
            });

The problem is getting that id back while deleting the item. I know there are many questions similar to this, some of them were good but I couldn't figure out to solve them. I had a look at this link solution but I wasn't able to solve

In adapter

 holder.deleteNoteIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            deleteNote(noteModel);
        }
    });


Method to delete

    private void deleteNote(ScheduleNote note, int itemPosition, View view) {
    mAuth = FirebaseAuth.getInstance();
    database = FirebaseFirestore.getInstance();

    //getting the doc id of auto-generated code in Firestore.
     String id = database.collection("notes").document(mAuth.getUid()).collection("mynotes").document().getId();

    Toast.makeText(context, "position " + itemPosition + "doc id " + id, Toast.LENGTH_SHORT).show();

    database.collection("notes").document(mAuth.getUid())
            .collection("mynotes")
            //.document("72NMkKY73CXHVN7DFE8W") get that id automatically
            .document(id)
            .delete()
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    //notifyDataSetChanged();
                    Snackbar snackbar = Snackbar.make(view, "Note Deleted successfully", Snackbar.LENGTH_SHORT);
                    snackbar.show();
                }
            });
}

id in the above variable isn't matching the real id. How to get that id?

I basically want two information for this :

  1. How to get the document Id before adding it to the Firestore so that I can attach this to my model class and later on delete based on that ID, has any solution?
  2. Or, just get the document Id by the Model Class that I pass when clicking on the item in RecyclerView?

I actually did a lot of research but couldn't figure it out. Any quick help would be appreciated, thanks.

Upvotes: 0

Views: 754

Answers (2)

androidLearner
androidLearner

Reputation: 1702

First of all add document to your collection without any data in it.

DocumentReference addedDocRef =database.collection("notes").document(mAuth.getUid())
            .collection("mynotes")
            .document();
log.i("Added document with ID: " + addedDocRef.getId());

Then add document id to your model class for later use.

Now, set data for document using your model class.

addedDocRef.set(scheduleNoteModel)

Upvotes: 1

Alex Mamo
Alex Mamo

Reputation: 138824

It doesn't seem to mee, that you are following this link solution. First of all, as also @Frank van Puffelen mentioned in his comment, "document().getId()" will always generate a brand new ID each time is called. So you should save that ID into a variable for later use, so you can delete the desired document right from the adapter. Your "ScheduleNote" class, besides the "noteTitle", "isImp", and "strDate" fields, should also contain a field called "id". So your declaration class should look like this:

class ScheduleNote {
    public String noteTitle, strDate, id;
    public boolean isImp;

    public ScheduleNote() {}

    public ScheduleNote(String noteTitle, String strDate, String id, boolean isImp) {
        this.noteTitle = noteTitle;
        this.strDate = strDate;
        this.id = id;
        this.isImp = isImp;
    }
}

Now, in your particular case, the following lines of code for adding the object to Firestore will do the trick:

CollectionRefference mynotes = database.collection("notes").document(mAuth.getUid())
        .collection("mynotes")
String docId = mynotes.document().getId();

To create an object of "ScheduleNote" type, please use:

ScheduleNote scheduleNoteModel = new ScheduleNote(noteTitle, strDate, docId, isImp);
//                                                                     ^
//                                                                newly added

To actually write the data to Firestore, please use:

mynotes.document(docId).set(scheduleNoteModel).addOnSuccessListener(/* ... */);
//                 ^

To be able to delete that document, you should use the following lines of code:

database.collection("notes").document(mAuth.getUid())
        .collection("mynotes")
        .document(id)
        .delete(note.id)
        .addOnSuccessListener(/* ... */);

And this is because, the following line generates again a new ID, which is not correct, as you need to use the one that was generated earlier:

String id = database.collection("notes").document(mAuth.getUid()).collection("mynotes").document().getId();

Upvotes: 2

Related Questions