2. Contacts Retrieval (Android 2.0+)

After using API Level 5, we can still only retrieve all contacts with a primary phone number only by:
Cursor cur = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.PHOTO_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
}, null, null, ContactsContract.Contacts._ID);
contacts.ensureCapacity(cur.getCount());
try {
if (cur.moveToFirst()) {
int idCol = cur.getColumnIndex(ContactsContract.Contacts._ID);
int photoCol = cur.getColumnIndex(ContactsContract.Contacts.PHOTO_ID);
int displayNameCol = cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int hasPhoneNumberCol = cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
do {
long id = cur.getLong(idCol);
long photoId = cur.getLong(photoCol);
String name = cur.getString(displayNameCol);
boolean hasPhoneNumber = cur.getInt(hasPhoneNumberCol) != 0;
ContactBean contact = new ContactBean(id, photoId, name);
contacts.add(contact);
// contactsMap.put(id, contact);
} while (cur.moveToNext());
}
} finally {
cur.close();
}

But in API Level 5, there is a new table structure. That is all details information about the contacts can be retrieved by a batch (not one by one).
         Cursor cur = contentResolver.query(CommonDataKinds.Phone.CONTENT_URI, 
         new String[] {
         CommonDataKinds.Phone.CONTACT_ID,
         CommonDataKinds.Phone.TYPE,
         CommonDataKinds.Phone.NUMBER,
         CommonDataKinds.Phone.IS_PRIMARY,
         }, null, null, CommonDataKinds.Phone.CONTACT_ID);
         try {
        if (cur.moveToFirst()) {
int idCol = cur.getColumnIndex(CommonDataKinds.Phone.CONTACT_ID);
int typeCol = cur.getColumnIndex(CommonDataKinds.Phone.TYPE);
int numberCol = cur.getColumnIndex(CommonDataKinds.Phone.NUMBER);
int isPrimaryCol = cur.getColumnIndex(CommonDataKinds.Phone.IS_PRIMARY);
        do {
        long id = cur.getLong(idCol);
                 int type = cur.getInt(typeCol);
        String number = cur.getString(numberCol);
        boolean primary = cur.getInt(isPrimaryCol) != 0;
        if (number != null) {
                                                       ....
        }
        } while (cur.moveToNext());
        }
         } finally {
         cur.close();
         }
By the contact ID obtained in the contact query and the contact ID from the phone query, we can group the phone numbers to be the details of contacts. This procedure is much faster than the method described in Contacts Retrieval (< Android 2.0). For 200+ contacts, it used about 1.3 second.

Comments