What i would like to talk about in this post is Contacts in android and how to add a new Contact to Android's Contact List. Initially i thought it was gonna be a simple thing to do but i gotta admit it, it was the first time i felt
a bit confused since I started android development. what happened was i wanted to write a piece of code to add a new contact when user selects one of our application menu options, I went to Android developers website(like i usually do) to find some clues on how to do that... as you might have already noticed there are some examples in Content Providers section about how to work with Contacts using People class, good, i was pretty sure that i got it... but when i started coding,Eclipse warned me that People class was deprecated... Beautiful!!!so what am i supposed to do if i shouldn't use People class, I was thinking with myself... having a look at People class documentation I found out that it's been replaced by a totally different mechanism and we should use another class called ContractsContact to interact with Contacts...
one of the things that struck me was the fact that there are more than two dozens classes and interfaces in android.provider package marked as deprecated and a completely different approach has been introduced for interacting with contracts since API level 5. this new API gives you a great level of flexibility and extensibility but as we all know everything has a price, if you want a flexible and extensible framework, no worries, but it comes with a bit more complexity, and I think it could be why they still prefer to stick with People class examples... ;)
Fair enough, here is the code that i used in our application to add a new Contact according to what user has already selected :
dont freak out ;) , although it might seem quite different than what you are familiar with, it's mostly because i used Batch insert technique and ContentProviderOperation.Builder class which have been introduced in API level 5.
you can still use getContentResolver().insert() and ContentValue objects but it is recommended to use new batch technique over traditional insert and update method.
what is important here is that you first need to create a RawContact and then use its ID to add some data like name, phone number and address, in traditional method you would need to insert a RawContact, get its ID and then use that ID in subsequent operations, I used withValueBackReference() method here which has been provided for handling these sort of cases when you are using batch technique.
You can find some good information about this whole thing in Data class documentation.