Sunday, March 4, 2012

Using the ContactsContract in phone lookup



This is very important that you make difference between

alt 1:  int contactID = c.getColumnIndexOrThrow(ContactsContract.Contacts._ID);

alt 2: String  contactID  = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));

If you use logcat to see the result you will see same contactID  if you use alt 1, but with alt 2 you will see different strings.
Be aware of this!
Sample code to lookup phone and e-mail using the latest class ContactsContract
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