For the impatient: skip the article, download the code.
Recently, when writing a physician directory for the Canton of Geneva, I wanted to include a feature for adding a new contact. That is, I wanted a button that would pop up the “Add a new contact” screen, with various fields (such as phone number, postal address, and email address) already filled in. Piece of cake, right?
Unfortunately, it turns out that the Android docs and Stack Overflow are pretty bereft of clear, concise instructions for creating a contact with multiple fields of various types, e.g. work phone, mobile phone, or home fax (if such a thing still exists).
Plus, the entire ContactsContract changed in API level 11 (Honeycomb), meaning that anything written for ICS or Jelly Bean wouldn’t work in Gingerbread, and vice-versa. Oh joy.
Luckily for you — assuming you stumbled across this post after a frustrated trip to Google — I’ve written a helper class to do all the heavy lifting. It provides a simple, fluent API that works for Android version 2.1 (Eclair) through 4.2 (Jelly Bean), and it’s open source.
You create a contact like this:
Intent intent = new AddContactIntentBuilder("Joe Blow") .addFormattedAddress("123 Fake Street, Springfield USA", StructuredPostal.TYPE_HOME) .addPhone("555-867-5309", Phone.TYPE_HOME) .addPhone("555-123-4567", Phone.TYPE_WORK) .addPhone("555-987-6543", Phone.TYPE_FAX_WORK) .addEmail("joe.blow@gmail.com", Email.TYPE_HOME) .addEmail("joe@blow.com", Email.TYPE_WORK) .build(); startActivity(intent);
And here’s what this code produces, in both Jelly Bean and Gingerbread:
Happy contact creating!