I would have listview and a lot of items inside. I want that user can long press on item and set it as Favorite. To do that, I need to get DB id to this menu on long press.
The ContextMenu.ContextMenuInfo
you get passed contains information about which item in the list was clicked. You can probably use this to get the information you need.
Update:
Somewhat like dziobas mentions in his answer you can do something like this to get to know which position the selected item has in your adapter:
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
long arrayAdapterPosition = menuInfo.position;
Now you know the position, and can fetch it from your ArrayAdapter
. If you have this ArrayAdapter
instance stored in a member variable (in this example I have named it myArrayAdapter), you can then proceed to get the item with ArrayAdapter.getItem(int position)
:
ToDoItem todoItem = (ToDoItem)myArrayAdapter.getItem(arrayAdapterPosition);
String task = todoItem.getTask();
int id = todoItem.getId();
You could now proceed to set the menu header title as follows:
menu.setHeaderTitle("Favorite: " + task + Integer.toString(id));
If your adapter supports getting Id, so it should look like this:
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
long id = menuInfo.id;
...