Search...

Tuesday, March 20, 2012

How to read contacts on Android ?


First, ensure that you have added android.permission.READ_CONTACTS to your AndroidManifest.xml file, then you can loop through your phone contacts like this:


Code:

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
   String contactId = cursor.getString(cursor.getColumnIndex(
   ContactsContract.Contacts._ID));
   String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
   if (Boolean.parseBoolean(hasPhone)) {
      // You know it has a number so now query it like this
      Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
      while (phones.moveToNext()) {
         String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));                
      }
   phones.close();
}

Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
   // This would allow you get several email addresses
   String emailAddress = emails.getString(
   emails.getColumnIndex(ContactsContract.CommonDataKinds.CommonDataColumns.DATA));
}
emails.close();
cursor.close();

No comments:

Post a Comment