我正在尝试从手机中删除特定联系人。我可以删除完整的联系人。如何使用联系人ID删除特定联系人。我想删除完整的数据,包括姓名,姓氏,电话号码,电子邮件,备注等......
答案 0 :(得分:5)
尝试以下代码:
final ArrayList ops = new ArrayList();
final ContentResolver cr = getContentResolver();
ops.add(ContentProviderOperation
.newDelete(ContactsContract.RawContacts.CONTENT_URI)
.withSelection(
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[] { selected_contact_IDfromlist })
.build());
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Delete This Contact!");
alertDialog.setMessage("Are you Sure you want to delete this contact?");
alertDialog.setButton(getString(R.string.callLog_delDialog_yes), new DialogInterface.OnClickListener() { // DEPRECATED
public void onClick(DialogInterface dialog, int which) {
try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
background_process();
ops.clear();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// System.out.println(" length :"+i);
}
return;
} });
alertDialog.setButton2(getString(R.string.callLog_delDialog_no), (DialogInterface.OnClickListener)null); // DEPRECATED
try {
alertDialog.show();
}catch(Exception e) {
// Log.e(THIS_FILE, "error while trying to show deletion yes/no dialog");
}
答案 1 :(得分:5)
如果您有contactId,则不需要使用 Contacts.CONTENT_LOOKUP_URI 。 事实上,我尝试使用它删除一些联系人的问题。
如果你有contactId的正确方法是直接使用ContactsContract.Contacts.CONTENT_URI:
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI,contactId);
int deleted = context.getContentResolver().delete(uri,null,null);
return deleted>0;
答案 2 :(得分:2)
在清单
中添加此内容<uses-permission android:name="android.permission.WRITE_CONTACTS" />
按ID代码删除联系人
private void deleteContactById(long id) {
Cursor cur = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts._ID + "="
+ id, null, null);
if (cur != 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);
resolver.delete(uri, ContactsContract.Contacts._ID + "=" + id, null);
} catch (Exception e) {
Log.e(TAG, "deleteContactById: ", e);
}
}
cur.close();
}
}
答案 3 :(得分:0)
public void deleteContact(Context context, String localContactId)
{
ContentResolver cr = context.getContentResolver();
String rawWhere = ContactsContract.Contacts._ID + " = ? ";
String[] whereArgs1 = new String[]{localContactId};
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, rawWhere, whereArgs1, null);
if(cur != null && cur.getCount() > 0) {
while (cur.moveToNext()) {
try{
String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
cr.delete(uri, null, null);
}
catch(Exception e)
{
System.out.println(e.getStackTrace());
}
}
}
if(cur != null)
cur.close();
}