I have finally got a working example of inserting and updating contacts using the new ContactsContract API, and I must say, it’s certainly not the prettiest API I’ve used. Sometimes it is downright malignant! I’m sure it made good sense when first created but I have found even the simplest actions like inserting an address somewhat of a chore.
The goal was to populate some values and display to the user the android edit screen. This could be done using the built-in USER_EDIT USER_INSERT or USER_INSERT_OR_UPDATE Activities like this:-
Intent i = new Intent(Intent.ACTION_INSERT);
i.putExtra(Insert.NAME, "Some Contact Name");
The problem here is that I CAN use
Insert.POSTAL to insert an address, but it will insert the whole address on the ‘street’ entry, not break them into suburb etc. which looks rubbish. From memory this is the same with display name, with everything being in the firstname field.
Trawling through the API. there looks to be a new field called ‘data’ which may allow more advanced interaction with contacts however this is only available in honeycomb so at least for the next few years (assuming that it works how I expect it) it isn’t feasable.
So this left me looking for another solution, which was to insert the contact before showing the edit screen. Again, this isn’t optimal, but I figured it was easier for the user to delete an unwanted contact than it was to fix addresses to appear in the correct fields. This on the whole worked well using the ContactsContract API:-
array of contentProviderOperations we wish to run
ArrayList ops = new ArrayList();
Add a new contact to a selected account (google in this case)
Add the display name. withValueBackReference is used as the user hasn’t been created yet. It will use the RAW_CONTACT_ID that will be created in the previous operation
Again using valueBackReference, we are inserting the phone number to the raw contact under a type of work.
Now to create the address insert operation. I have marked it as a work address, and we specify each item in the address.
ContentProviderOperation.Builder operationBuilder = ContentProviderOperation
Last thing to do is to run the batch operation
Uri contactUri = _context.getContentResolver().applyBatch(
The URI returned from the batch operation can be used to bring up the Edit User Activity:-
Intent i = new Intent(Intent.ACTION_EDIT);
I also do this within an AsyncTask as the UI will become unresponsive for a few seconds.
I will cover updates in part 2
Any questions, comments or suggestions, feel free to post a comment below.