Vinay Vinay - 19 days ago 9
Android Question

Android Applicaiton - How to get birthday of a contact

I am working on an android application for which I need to match the birthday of each contact against current date and if positive, process some business logic, which needs the complete contact details.

I have found ways to read birthdays of contacts or the contacts themselves separately, but am confused as to how to combine both. Can somebody please provide some direction.

Thanks

Answer

Found the answer after some looking out on the web. The way this has to be done is :

  • Get list of contacts
  • For each contact, get contactId
  • Get birthday using the contactid

Following is the code snippet :

ContentResolver cr = getContentResolver(); //getContnetResolver()
String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };

Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, projection, null, null,
            ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");

while (cur.moveToNext()) {

   Map<String, String> contactInfoMap = new HashMap<String, String>();
   String contactId = cur.getString(cur.getColumnIndex(ContactsContract.Data._ID));
   String displayName =  cur.getString(cur.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));     

    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 birthdayCur = cr.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder); 
    if (birthdayCur.getCount() > 0) {
        while (birthdayCur.moveToNext()) {
             String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
        }
    }
    birthdayCur.close();

   }    

    cur.close();
Comments