Search code examples
androidandroid-recyclerviewandroid-alertdialogadapter

How to display an AlertDialog on ClickListener in a RecyclerView Adapter


I want to display an Alert Dialog for the user when he presses on the delete ImageButton. However, the app crashes when the button is pressed.

This is the code inside the Adapter for the onClickListener:

holder.delete.setOnClickListener(new View.OnClickListener() {
            String productId = String.valueOf(item.getId());
            @Override
            public void onClick(View v) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(mCtx);
                alertDialog.setTitle("App Name");
                alertDialog.setMessage("Are you sure you want to delete this item?");
                alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteItem(productId);
                        dialog.cancel();
                    }
                });
                alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                          dialog.cancel();
                    }
                });

                AlertDialog dialog = alertDialog.create();
                dialog.show();
            }
        });

This is what my LogCat looks like : The error is in this line :

AlertDialog dialog = alertDialog.create();

enter image description here


Solution

  • AlertDialog.Builder alertDialog = new AlertDialog.Builder(mCtx);
    

    Dialogs need activity. If you pass context you will receive an error

    Use interface for onclickListener and implement in your activity then pass your activity to your dialog!