I have code to read contact details and to read birthdays. But how do I get a list of contacts in order of their upcoming birthday?
For a single contact identified b
I did this the other way round - a selection directly to Data table which stores birthday.
private static final int UPCOMING_COUNT = 10;
public static List upcomingBirthday(Context ctx) {
String today = new SimpleDateFormat("MM-dd").format(new Date());
List firstPart = upcomingBirthday(ctx, today, "12-31", UPCOMING_COUNT);
if (firstPart.size() < UPCOMING_COUNT) {
firstPart.addAll(upcomingBirthday(ctx, "01-01", today, UPCOMING_COUNT - firstPart.size()));
}
return firstPart;
}
public static List upcomingBirthday(Context ctx, String fromDate, String toDate, int rows) {
Uri dataUri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
ContactsContract.CommonDataKinds.Event.START_DATE
};
Cursor c = ctx.getContentResolver().query(
dataUri,
projection,
ContactsContract.Data.MIMETYPE + "= ? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" AND substr(" + ContactsContract.CommonDataKinds.Event.START_DATE + ",6) >= ?" +
" AND substr(" + ContactsContract.CommonDataKinds.Event.START_DATE + ",6) <= ?" ,
new String[] {ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE, fromDate, toDate},
"substr("+ ContactsContract.CommonDataKinds.Event.START_DATE +",6)");
List result = new ArrayList();
int i=0;
while (c.moveToNext() && i
}
The SELECT is called twice - one call from today to 12/31 and second call from 01/01 to today. I limit returned rows to 10 but this is not necesarry.
EDIT: I found that this won't work on all Android phones as birthday dates are stored in many different format. So you have to load all birthdays (unordered), parse it and sort it in memory. #Fail