Android: Retrieve contact name from phone number

Noah Seidman picture Noah Seidman · Jun 20, 2010 · Viewed 63.7k times · Source

I would like to retrieve the name of a contact associated with an incoming telephone number. As I process the incoming number in the broascastreceiver having a String with the name of the incoming caller would help my project greatly.

I would think this involves a query using the sql WHERE clause as a filter, but do I need to sort the contacts? An example or hint would be of great assistance.

Answer

Vikram.exe picture Vikram.exe · Aug 5, 2013

Although this has already been answered, but here is the complete function to get the contact name from number. Hope it will help others:

public static String getContactName(Context context, String phoneNumber) {
    ContentResolver cr = context.getContentResolver();
    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
    Cursor cursor = cr.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
    if (cursor == null) {
        return null;
    }
    String contactName = null;
    if(cursor.moveToFirst()) {
        contactName = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
    }

    if(cursor != null && !cursor.isClosed()) {
        cursor.close();
    }

    return contactName;
}

[Updating based on Marcus's comment]

You will have to ask for this permission:

<uses-permission android:name="android.permission.READ_CONTACTS"/>