Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ContentProviderOperation to update and insert contacts

Tags:

android

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

like image 457
Bogus Avatar asked Jun 02 '10 10:06

Bogus


1 Answers

You must provide a where clause for each ContentProviderOperation if you want to do an update, See here and here.

like image 117
David-mu Avatar answered Oct 21 '22 19:10

David-mu