Ravi Bhandari
Ravi Bhandari

Reputation: 4698

Check Incoming number is stored in Contacts list or not android

In my android app when an incoming call i want to show my custom ui and i am able to do this. No i want to check incoming number is from contacts or not. Below is my code for doing so but it returns null for an incoming number which is stored in my contacts list.

public String findNameByNumber(String num){
    Uri uri = Uri.withAppendedPath(Phones.CONTENT_FILTER_URL, Uri.encode(num));

    String name = null;
    Cursor cursor = mContext.getContentResolver().query(uri, 
                        new String[] { Phones.DISPLAY_NAME }, null, null, null);
    if (cursor != null && cursor.moveToFirst()) {
        name = cursor.getString(cursor.getColumnIndex(Phones.DISPLAY_NAME));
        cursor.close();
        callyName.setText(name+" Calling..");
    }
    return name;
}

and i have incoming call from a number say+917878787878 but in my contacts this contact is stored as name XYZ with number 78 78 787878,which is formated because between number there are space.and also try by excluding +91 but still it returns null. So how can i find number which is stored in any format.Which may be stored with country code or not.

Thanks In advance.

Upvotes: 2

Views: 2806

Answers (1)

Mohammed Ali
Mohammed Ali

Reputation: 2926

Try this code instead (using PhoneLookup.CONTENT_FILTER_URI instead of Phones):

String res = null;
    try {
        ContentResolver resolver = ctx.getContentResolver();
        Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
        Cursor c = resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);

        if (c != null) { // cursor not null means number is found contactsTable
            if (c.moveToFirst()) {   // so now find the contact Name
                res = c.getString(c.getColumnIndex(CommonDataKinds.Phone.DISPLAY_NAME));
            }
            c.close();
        }
    } catch (Exception ex) {
        /* Ignore */
    }        
    return res;

As docs says ContactsContract.PhoneLookup: A table that represents the result of looking up a phone number, for example for caller ID. To perform a lookup you must append the number you want to find to CONTENT_FILTER_URI. This query is highly optimized.

Upvotes: 6

Related Questions