Step 3

Now that the we've registered our ListView for a context menu and defined our context menu item, we need to handle the callback when it is selected. For this, we need to identify the list ID of the selected item, then delete it. So fill in the onContextItemSelected() method like this:

public boolean onContextItemSelected(MenuItem item) {

switch(item.getItemId()) {

case DELETE_ID:

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

mDbHelper.deleteNote(info.id);

fillData();

return true;

return super.onContextItemSelected(item);

Here, we retrieve the AdapterContextMenuInfo with getMenuInfo(). The id field of this object tells us the position of the item in the ListView. We then pass this to the deleteNote() method of our NotesDbAdapter and the note is deleted. That's it for the context menu — notes can now be deleted.

0 0

Post a comment