Search code examples
androidandroid-alertdialogbaseadapterappcompatactivity

Make alert dialog in BaseAdapter extended class


I have a MyListAdapter Java class that it like below:

class MyListAdapter extends BaseAdapter implements TextToSpeech.OnInitListener{

now I want to make a confirmation dialogue on each list items like below:

btnDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {




            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("Delete");
            alert.setMessage("Are you sure?");
            alert.setPositiveButton(android.R.string.yes,
            new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                            // continue with delete
                new DatabaseHelper(context).deleteEmployee(employees.get(position));
                employees.remove(position);
                notifyDataSetChanged();
                        }
                    });

But on

AlertDialog.Builder alert = new AlertDialog.Builder(this);

I have an error that it say:

builder (android.content.Context)    in Builder cannot be applied to (anonymous android.view.View.OnClickListner)

I don't have any problem when my class extends from AppCompatActivity


Solution

  • The problem is your trying to pass this as a Context, but it's pointing to your View.OnClickListener.

    Replace:

    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    

    With:

    AlertDialog.Builder alert = new AlertDialog.Builder(view.getContext());