I got a application with a listView in which I setup data from my sqlite database. My CustomCursorAdapter is placing the data (from the DBAdapter) in the listview.
I want to get the item id of the selected item from my listView, I got it working via this code:
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
//Get it from the database.
String countryCode =
cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0)));
Toast.makeText(getApplicationContext(),
countryCode, Toast.LENGTH_SHORT).show();
}
});
That code does get the ID and makes a toast in which I can see the ID. This works perfectly.
Now I want to put it in a context menu in which I long click the item (so this method does not start). I have the context menu working with the items, but I only need to get the id of which item in the listview is selected.
This is now my code for the context menu:
public boolean onContextItemSelected(MenuItem item) {
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
String countryCode =
cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0)));
switch (item.getItemId()) {
case CONTEXT_MENU_DELETE_ITEM:
Toast.makeText(getApplicationContext(),
countryCode, Toast.LENGTH_SHORT).show();
return(true);
case CONTEXT_MENU_UPDATE:
return(true);
}
return(super.onOptionsItemSelected(item));
}
The context menu does not work now because the position variabele is not set. I really dont know how to get the selected item.
Thanks in advance.
Use this