Psypher Psypher - 4 months ago 17
Android Question

Getting ContactName using phone number

I am creating an activity which lists out recent calls from a user. The requirement is that when a user receives the call,the

phone number
and
contact name
is stored in DB to be later displayed in the activity. To retrieve the contact Name the phone number is matched with the contacts in the users contact list. I am using below code to get the contact name.

(Below code queries the Contact database and finds a match to the inputted phone number)

String getContactDisplayNameByNumber(String number) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String name = "";

Cursor contactLookup = context.getContentResolver().query(uri, new String[]{
ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);

try {
if (contactLookup != null && contactLookup.moveToNext()) {
name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
Log.v("ranjapp", "Name is " + name + " Number is " + number);
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
return name;
}


Now the problem is the phonenumber is saved in the contact list as "1234567891" and the phone number retrieved from an incoming call is "01234567891"(0 prefixed).
As 0 is prefixed in the incoming number the number is not matching with the number in contact list.

There can be also other possibilities the incoming number may have the country code prefixed and saved contact does not have it.

How can i match in these scenarios.

(I am aware of
PhoneNumberUtils.compare()
but not able to apply it in the code mentioned).

Answer

The problem was the method was not getting called with the phone number as input. It works irrespective how the number is i.e with prefix +91 or 0. Corrected the code as below:

Bundle bundle = intent.getExtras();
String number = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
String name=getContactDisplayNameByNumber(number);
Comments