Using ContentProviderOperation to update and insert contacts

Posted by Bogus on Stack Overflow See other posts from Stack Overflow or by Bogus
Published on 2010-06-02T10:06:06Z Indexed on 2010/06/02 10:23 UTC
Read the original article Hit count: 649

Filed under:

Hello,

I faced the problem updating/insertng contacts on Android 2.0+. There is no problem to insert a new contact when phone book is empty but when I did it 2nd time some fileds like TEL, EMAIL are doubled and tripped etc. but N, FN, ORG are ok (one copy).

After getting and advice of other member this forum I updated a contact first and then ContentProviderResult[] returned uri's with null then I do an insert action and it went ok but after that I made an update and all contacts are aggregated into one - i got 1 contact insted 3 which existed in phone book. This one was damaged, the contact fields are randomly built.

I set Google account.

Code:

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
  ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI)
    .withValue(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DISABLED)
    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName)
    .build()); 

// add name
ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
   builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
   builder.withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.PHONETIC_FAMILY_NAME, name);

// phones
ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
   builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
   builder.withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
   builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneValue);
   builder.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, phoneType);
   builder.withValue(ContactsContract.CommonDataKinds.Phone.LABEL, phoneLabel);         
   ops.add(builder.build());

// emails ...
// orgs ...

try {

  ContentProviderResult[]  result = mContentResolver.applyBatch(ContactsContract.AUTHORITY, ops);   
 }
  } catch (Exception e) {
   Log.e(LOG_TAG, "Exception while contact updating: " + e.getMessage());
  }

What is wrong in this solution ? How does work aggregation engine ?

I will be glad for help.

Bogus

© Stack Overflow or respective owner

Related posts about android