Kamil
Kamil

Reputation: 113

Handle id of the Cloud Firestore document from RecyclerView

I'm doing deletion with Cloud Firebase. I have a code that delete the document:

db.collection ( "cities"). document ( "DC")
        .Delete ()
        .addOnSuccessListener (new OnSuccessListener <Void> () {
            @Override
            public void onSuccess (Void aVoid) {
                Log.d (TAG, "DocumentSnapshot successfully deleted!");
            }
        })
        .addOnFailureListener (new OnFailureListener () {
            @Override
            public void onFailure (@NonNull Exception e) {
                Log.w (TAG, "Error deleting document", e);
            }
        });

I need to get the id value of the document that is currently in RecyclerView. I would like it to work with onLongPress.

To handle item on long click on recycler view - I found this code:

class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
    private Article article;

    private TextView nameTextView;

    public ViewHolder (View itemView) {
        super (itemView);
        itemView.setOnClickListener (this);
        itemView.setOnLongClickListener (this);
        nameTextView = (TextView) itemView.findViewById (R.id.grid_item_article_name_textView);
    }

    public void bind (Article article) {
        this.article = article;
        nameTextView.setText (article.getName ());
    }

    @Override
    public void onClick (View view) {
        // Context context = view.getContext ();
        // article.getName ()
    }

    @Override
    public boolean onLongClick (View view) {
        // Handle long click
        // Return true to indicate the click was handled
        return true;
    }
}

How to get document id from Firestore?

Edit: MainFragment - https://codepaste.net/idih7i MainActivity - https://codepaste.net/9q019e

Upvotes: 2

Views: 923

Answers (1)

Gaurav Rai
Gaurav Rai

Reputation: 370

You can the fetch document ID by using a response object you generate from the Firestore Query, Here is sample code for that:

String myId = response.getSnapshots().getSnapshot(position).getId();

This will give you the Id of the document from inside the ViewHolder.

Upvotes: 1

Related Questions