There is no shortcut in getting a contact’s age in Android. What I did instead was to get the birthday of the contact (if any is provided) and subtracted that from the current year.
The output of a contact’s birthday is a string formatted date with dashes (-) so I had to make a helper method to parse it; get the month, date and year; convert it to a Date object, then do calculation to get the age of the contact.
Check out the helper method below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public static int calculateAge(int year, int month, int day) { Date now = new Date(); int nowMonth = now.getMonth()+1; int nowYear = now.getYear()+1900; int result = nowYear - year; if (month > nowMonth) { result--; } else if (month == nowMonth) { int nowDay = now.getDate(); if (day > nowDay) { result--; } } return result; } |
And this is how I retrieved the birthday of the contact from the contact list. Once retrieved, I parsed the output and passed it to the calculateAge() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public static int getAge(Context ctx, String contactId) { int age = 0; ContentResolver cr = ctx.getContentResolver(); String columns[] = { ContactsContract.CommonDataKinds.Event.START_DATE, ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.MIMETYPE, }; String where = Event.TYPE + "=" + Event.TYPE_BIRTHDAY + " and " + Event.MIMETYPE + " = '" + Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contactId; String[] selectionArgs = null; String sortOrder = ContactsContract.Contacts.DISPLAY_NAME; Cursor cur = cr.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder); if (cur.getCount() > 0) { while (cur.moveToNext()) { String[] sage = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE)).split("-"); age = calculateAge(sage[0], sage[1], sage[2]); } } cur.close(); return age; } |