In the course of programming an android app, I needed access to all contacts who had addresses entered. I couldn’t find good example code on the internet — most code either targets the wrong API level (Android 1.6, the contacts API was changed for 2.2), or had nothing to do with grabbing address data. With help from StackOverflow, here’s example code for anyone trying to work with Android’s new Contacts API.
First, you need to specify android.permission.READ_CONTACTS in your AndroidManifest.xml file, since we’re only going to read contact data, not write to it.
According to ContactsContract.Data, contact Data tables are implicitly joined with the ContactsContract.Contacts table. So, all we need to do is query the ContactsContract.CommonDataKinds.StructuredPostal table and we’ll still have access to important data like their display name.
Find the column names of the data you want. ID_COLUMN is the column name of the id of a contact, LOOKUP_KEY_COLUMN is the column name of the key you can use to lookup the contact, NAME_COLUMN is the column name of the display name of the contact, ADDRESS_COLUMN is the column name of the formatted address of the contact.
private static final String ID_COLUMN = ContactsContract.Contacts._ID;
private static final String LOOKUP_KEY_COLUMN = ContactsContract.Contacts.LOOKUP_KEY;
private static final String NAME_COLUMN = ContactsContract.Contacts.DISPLAY_NAME;
private static final String ADDRESS_COLUMN = ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS;
Next, we can access all contacts that have an address with the following method:
public static void getAllContacts(Activity context) {
Cursor cursor = context.getContentResolver()
.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex(ID_COLUMN));
String lookup = cursor.getString(cursor.getColumnIndex(LOOKUP_KEY_COLUMN));
String displayName = cursor.getString(cursor.getColumnIndex(NAME_COLUMN));
String address = cursor.getString(cursor.getColumnIndex(ADDRESS_COLUMN));
Log.d("Traffic", "Contact " + id + ": | Lookup key: " + lookup + " | Name: " + displayName + " | Address: " + address);
}
cursor.close();
}
Hope this code helps anyone struggling to read contact information.