Monday, August 29, 2011

Android - Find contact by phone number

In one of my previous article Receiving SMS, I explained how to receive sms and promised to cover how to find the sender contact details.

In this article, I will explain how to lookup an android contact by phone number. There are numerous use cases where you would need this functionality.

private String findContactByNumber(Context ctx,String phoneNumber){
ContentResolver resolver=ctx.getContentResolver();
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));
String[] phoneNoProjections = { PhoneLookup._ID,PhoneLookup.DISPLAY_NAME };
Cursor cursor = resolver.query(lookupUri,phoneNoProjections, null, null, null);
try {
if (cursor.moveToFirst()) {
Log.d("Contacts Example:","Contact found");
return cursor.getString(1);
}
Log.d("Contacts Example","lookup completed");
} finally {
if (cursor != null)
cursor.close();
}
return null;
}

In line#7, we specify the fields(columns) that we are interested in. Only these information about a contact will be retrieved. Suppose if you want other information about the contact, then you would have to add it to the array. For a complete list of fields that can be queried refer PhoneLookup API.