'How to delete a specific document node on Firestore (Android Studio)

What i'm trying to achieve is user able to select which document they want to delete. After they press delete button on a specific recycle view column, the data will be deleted. I'm able to create the recycler view by showing all the documents inside the firestore, but how can I know which unique ID to be deleted when the user select a specific data ? Currently i done the delete function but the document path are hard-coded, thats mean when i click on delete button it only can delete AAIZ9QeIRueS7q9xaAn3MCboVfv2. How can I make the document path to be dynamic?

My firestore enter image description here

My View Holder

class MyViewHolder extends RecyclerView.ViewHolder {
    Button deletebutton;
    TextView name,phone,email,position;
    FirebaseAuth fAuth;
    FirebaseFirestore fStore;
    public MyViewHolder(@NonNull @NotNull View itemView) {
        super(itemView);
        deletebutton =itemView.findViewById(R.id.delete_button);
        //firebase auth instances assign
        fAuth = FirebaseAuth.getInstance();
        fStore = FirebaseFirestore.getInstance();
        name=itemView.findViewById(R.id.name_text);
        phone=itemView.findViewById(R.id.surname_text);
        email=itemView.findViewById(R.id.email_text);
        position=itemView.findViewById(R.id.position_text);

        deletebutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData();
            }
        });



    }
    private void getData(){
        FirebaseFirestore db = FirebaseFirestore.getInstance();
        DocumentReference noteRef = db.collection("Users").document("AAIZ9QeIRueS7q9xaAn3MCboVfv2");

        noteRef.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull @NotNull Task<Void> task) {
                if(task.isSuccessful()){
                    Log.d("TAG","delete");
                }
                else{
                    Log.d("TAG","error");

                }
            }
        });
    }
}

enter image description here



Solution 1:[1]

Firstly, wherever you are creating this document you need to add a field firebaseUid in which you will store the document id. The document that will be created now will have 5 fields fullName, phoneNumber, position, emailAddress, firebaseUid.

Now create a model class for your adapter to get and set the data in recycler view. Then, using model class fetch the firebaseUid and delete the document.

Below is the code snippet of model class and to delete documents that I have implemented in my application.

public class UserDetailModel {

    private String name;
    private String email;
    private String phone;
    private String designation; 
    private String firebaseUid; 

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }

    public String getFirebaseUid() {
        return firebaseUid;
    }

    public void setFirebaseUid(String firebaseUid) {
        this.firebaseUid = firebaseUid;
    }

}

Delete a Document:

mFirebaseFireStore.collection("users").document(model.getFirebaseUid()).delete().addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if(task.isSuccessful()){
           //Log.d(TAG, "User account deleted.");
        }
    }
});

Solution 2:[2]

Case 1: If you don't already have stored the unique user ID at the time of new user creation in firestore field.

--------------------> SOLUTION

You need to have the document ID* which you want to delete on button click [in case you haven't stored the auto-generated ID or assigned docID by yourself in firetore i.e., document fields -> ] so in this case, you need to get the specific document ID and for that, you have to use a where [where clause] query ad inside this where clause, you can get docID and can then use the docID inside the delete query [but note that the document must exist otherwise the app will crash] like in your case you can do something like this:

--------------------> CODE:

dbroot.collection("Users")
.whereEqualTo("emailAddress",UsersInfo.get(position).getEmail()) //your Users model class getEmail method to get current user info. [in recyler view adapter onBind method]
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                            @Override
                            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                                if (task.isSuccessful()) {
                                    if(task.getResult().size() > 0) //if document exits
                                    {
                                        for (DocumentSnapshot d : task.getResult())
                                        {
                                            String docID = d.getId(); //get the docID [which you want to delete]

                                            //Toast.makeText(getContext(), "docID: "+docID , Toast.LENGTH_SHORT).show();

                                            dbroot.collection("Users").document(docID).delete(); //here provide the above stored unique docID [which have to be deleted inside delete query]
                                            
                    Toast.makeText(getContext(), "DELETED Successfully", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                    else if(task.getResult().size() <= 0) //if document doesn't exists
                                    {
                                        Toast.makeText(getContext(), "No such user exists!", Toast.LENGTH_SHORT).show();

                                    }
                                }
                                else
                                {
                                    Log.d(TAG, "Error getting documents: ", task.getException());
                                    Toast.makeText(getContext(), "A system ERROR occurred, please try again", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

Case 2: you can store docID as other fields like emailAddress etc. at the time of creation of new user through hashmap or Users model class [this case is already answered above]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeevandeep Saini
Solution 2 cigien