How to delete a contact?

2020-07-11 10:09发布

问题:

I'm working at android 2.1 ContactContract, when I had not set account(for example: gmail account) to android emulator then, new a contact, but could not delete this contact at DB.

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    String[] args = new String[] {id};
    ops.add(ContentProviderOperation.newDelete(Data.CONTENT_URI)
            .withSelection(Data.CONTACT_ID + "=?", args)
            .build());
    ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)
             .withSelection(RawContacts.CONTACT_ID + "=?", args)
             .build());
    ops.add(ContentProviderOperation.newDelete(Contacts.CONTENT_URI)
             .withSelection(Contacts._ID + "=?", args)
             .build());

回答1:

Deleting the contact from RawContacts will delete the data from Data, Contacts table.

ArrayList ops = new ArrayList(); String[] args = new String[] {id}; 
// if id is raw contact id
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI).withSelection(RawContacts._ID + "=?", args) .build()); 
    OR
// if id is contact id
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI).withSelection(RawContacts.CONTACT_ID + "=?", args) .build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);



回答2:

public static boolean fullDeleteContactByRawId(String rawId)
{
    Uri rawUri = RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
    String where = RawContacts._ID + " = ?";
    String[] args = new String[]{rawId};

    try
    {
        ContentManager.delete(rawUri, where, args);
    }
    catch(Exception e)
    {
        return false;
    }

    return true;
}

notice: After full delete ,this contact can not sync



回答3:

I use this to delete a phone number from an existing contact, but not the contact itself:

    ArrayList ops = new ArrayList();
    String[] args = new String[]{
        ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
        number,
        Integer.toString(ContactsContract.CommonDataKinds.Phone.TYPE_MAIN),
        raw_contact_id
    };
    ops.add(
        ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
            .withSelection(ContactsContract.Data.MIMETYPE + "=? AND "
                + ContactsContract.CommonDataKinds.Phone.NUMBER + "=? AND "
                + ContactsContract.CommonDataKinds.Phone.TYPE + "=? AND "
                + ContactsContract.Data.RAW_CONTACT_ID + "=?"
                , args)
            .build());

    c.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);