The method below happens when an item in a ListActivity is long pressed. The idea is to delete that item from the database and for that I need to call mNotesAdapter.deleteNote(ID). Which works fine if I don’t use an AlertDialog; but I should use one for delete confirmations. But I don’t know how to pass the menu info, or the id itself to the onClick method.
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)item.getMenuInfo();
switch (item.getItemId()) {
case R.id.contextmenu_item_remove:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to delete this note?");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// VARIABLE menuInfo IS NOT ACCESSIBLE HERE, NOW WHAT?
mNotesAdapter.deleteNote(menuInfo.id);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
return true;
}
return super.onContextItemSelected(item);
}
You should be able to access the reference if you mark it as
final.To answer the other question in your comment,
finaldoesn’t mean the contents of the object can’t be changed. It just means that the reference can’t move to another object.When you enter that method, you’re immediately creating a new reference to a new
AdapterContextMenuInfoin the first line. Then you’re creating a newOnClickListenerthat will only act on that one object thatmenuInfois creating.