1

In my application I try to search a contact using the phonenumber. The phonenumber I am searching with is always in the same format ('123456789' for example). But the following code retrieves not all contacts I expected. The main issue might be the different format of phonenumbers in my phone: some contacts are saved with '+12 345 6789', the other with '0123 456789'. Although I tried ContactsContract.PhoneLookup.NORMALIZED_NUMBER my code retrieves only the contacts saved with phonenumbers in the '123456789'-format.

private String getContactDetails(Context context, String number) {
    String[] projection = new String[] {
            ContactsContract.PhoneLookup.DISPLAY_NAME,
            ContactsContract.PhoneLookup._ID,
            ContactsContract.PhoneLookup.LOOKUP_KEY};
    int len = number.length();
    Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number.substring(len-7)));
    String selection = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        selection = ContactsContract.PhoneLookup.NORMALIZED_NUMBER + " LIKE %" + number.substring(len-7) + "%";
    }
    Cursor cursor = context.getContentResolver().query(contactUri, projection, selection, null, null);
    String name = null;
    if(cursor != null) {
        if (cursor.moveToFirst()) {
            name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
        }
        cursor.close();
    }
    return name;
}
Timitrov
  • 211
  • 1
  • 3
  • 14

1 Answers1

1

Don't use both PhoneLookup.CONTENT_FILTER_URI with selection, CONTENT_FILTER_URIs are used to search for data using the URI itself, and should not get any selection.

The PhoneLookup.NORMALIZED_NUMBER column is for getting the result back in an e164 format, not for querying.

Try this:

Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode("123456789"));
String[] projection = new String[] { PhoneLookup.NUMBER, PhoneLookup.NORMALIZED_NUMBER };
Cursor c = getContentResolver().query(uri, projection, null, null, null);
if (c != null) {
    if (c.moveToFirst()) {
        String number = c.getString(0);
        String e164_number = c.getString(1);
        Log.d(TAG, "number=" + number + ", e164=" + e164_number);
    } else {
        Log.d(TAG, "couldn't find number");
    }
}
c.close();
marmor
  • 27,641
  • 11
  • 107
  • 150