Get birthday for each contact in Android application

caw picture caw · Dec 20, 2011 · Viewed 13k times · Source

In my android application, I read out all the contacts with the following code:

ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
    while (cur.moveToNext()) {
        String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
        String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        ContentResolver bd = getContentResolver();
        String where = Data.RAW_CONTACT_ID+" = "+id+" and "+Data.MIMETYPE+" = "+CommonDataKinds.Event.CONTENT_ITEM_TYPE;
        Cursor bdc = bd.query(ContactsContract.Data.CONTENT_URI, null, where, null, null);
        if (bdc.getCount() > 0) {
            while (bdc.moveToNext()) {
                String birthday = bdc.getString(0);
                Toast.makeText(getApplicationContext(), id+name+birthday, Toast.LENGTH_SHORT);
            }
        }
    }
}
cur.close();

This is how I tried to read out the birthday event for every single contact. But obviously it doesn't work yet. So how can I read out the contact's date of birth correctly?

Answer

dstricks picture dstricks · Dec 26, 2011

Word of caution: some OEM's provide their own contact provider (not the standard Android one) and may not follow standard Android practices. For example, com.android.providers.contacts.HtcContactsProvider2 responds to queries on my HTC Desire HD

Here is one way:

// method to get name, contact id, and birthday
private Cursor getContactsBirthdays() {
    Uri uri = ContactsContract.Data.CONTENT_URI;

    String[] projection = new String[] {
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Event.CONTACT_ID,
            ContactsContract.CommonDataKinds.Event.START_DATE
    };

    String where =
            ContactsContract.Data.MIMETYPE + "= ? AND " +
            ContactsContract.CommonDataKinds.Event.TYPE + "=" + 
            ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
    String[] selectionArgs = new String[] { 
        ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE
    };
    String sortOrder = null;
    return managedQuery(uri, projection, where, selectionArgs, sortOrder);
}

// iterate through all Contact's Birthdays and print in log
Cursor cursor = getContactsBirthdays();
int bDayColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
while (cursor.moveToNext()) {
    String bDay = cursor.getString(bDayColumn);
    Log.d(TAG, "Birthday: " + bDay);
}

If this doesn't work, you may have an OEM modified contacts provider.