I have a listview and I called registerForContextMenu. In the ContextMenu I only have one menu is “Delete Contact”. Below is the code when it is clicked delete menu:
public boolean onContextItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case DELETE_ID:
AdapterView.AdapterContextMenuInfo menuinfo;
menuinfo = (AdapterContextMenuInfo)item.getMenuInfo();
int id = menuinfo.position;
delete(id);
return true;
}
return super.onContextItemSelected(item);
}
private void delete(int id)
{
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, ContactsContract.Contacts._ID + "=" + id, null, null);
while (cur.moveToNext()) {
try{
String lookupKey = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.
Contacts.CONTENT_LOOKUP_URI, lookupKey);
System.out.println("The uri is " + uri.toString());
cr.delete(uri, ContactsContract.Contacts._ID + "=" + id, null);
}
catch(Exception e)
{
System.out.println(e.getStackTrace());
}
}
}
But with the above code there is no detail data is erased.
My question is whether any of the above code is missing or if it is incorrect?
You’ll want to use the
idfrom theAdapterContextMenuInfo:Right now you’re using the
position, which represents the position of the selected row in the adapter and not theidof the contact for that particular row so when you look for the contact with thatidyou’ll, most probably, not find it.