Tom Tom - 2 months ago 9
Java Question

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!

Answer

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