Question

Following is working for inserting a new contact:

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
      .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
      .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
      .build());

ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
      .withValueBackReference(Data.RAW_CONTACT_ID, 0)
      .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
      .withValue(StructuredName.GIVEN_NAME, given_name)
      .build());

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

I'd like to switch to ContentValues as it is more flexible.

However, it fails when I change to ContentValues as follows:

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
      .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
      .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
      .build());

ContentValues values = new ContentValues();
values.put(StructuredName.GIVEN_NAME, given_name)
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
      .withValues(values).build()); 

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

This only adds an empty contact.

Looks like I should call something like withValueBackReference() in my new version, but don't know how to do it. Any ideas?

Was it helpful?

Solution

Turned out we should get the raw contact id for insert:

    ContentResolver resolver = getContentResolver();
    Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");

    ContentValues values = new ContentValues(); 
    long id = ContentUris.parseId(resolver.insert(uri, values));
    uri = Uri.parse("content://com.android.contacts/data");

    values.put("raw_contact_id", id);
    values.put(StructuredName.GIVEN_NAME, given_name)
    resolver.insert(uri, values);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top