1

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);
}
rfgamaral
  • 16,546
  • 57
  • 163
  • 275
  • 1
    Maybe in times like this it's best to have an actual class that implements `OnClickListener()` so you can have a custom constructor to pass the item in to. Also, shouldn't it be accessible if you make `menuInfo` a final reference? – DeeV Sep 27 '11 at 18:09
  • 1
    It does become accessible and I just tested it in the emulator and works fine. I just don't get it lol... Since it's final, how come every time an option in the context menu is selected, a new `menuInfo` with new data is created? Is it because it's declared in the local scope of a method and will be destroyed in the end? Do a proper answer below so I can mark it as accepted please. – rfgamaral Sep 27 '11 at 18:21

1 Answers1

2

You should be able to access the reference if you mark it as final.

To answer the other question in your comment, final doesn'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 AdapterContextMenuInfo in the first line. Then you're creating a new OnClickListener that will only act on that one object that menuInfo is creating.

DeeV
  • 35,865
  • 9
  • 108
  • 95