简体   繁体   中英

Error in Alert dialog on this

This is my code,

b3.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        if (v == b3) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Delete")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            mydb.deleteContact(id_To_Update);
                            Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // User cancelled the dialog
                        }
                    });
            AlertDialog d = builder.create();
            d.setTitle("Are you sure");
            d.show();
        }
    }

});

if (!rs.isClosed()) {
    rs.close();
}
name.setText(nam);
email.setText(emai);

When I use this code on a delete button an error appear on first "this". How to solve it? How can I use delete confirmation message?

Please help me. Thanks in advance!

Use context instead of simply "this" reference. Here you can use Activity context, not any other context. For more information visit these links Context , AlertDialog.Builder

For activity:

 AlertDialog.Builder builder = new AlertDialog.Builder(ActivityName.this);

For fragment:

 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

Thanks

You need to replace

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

with

AlertDialog.Builder builder = new AlertDialog.Builder(YourActivityName.this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM