0

I am using below code for getting incoming call number which works fine.

String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);

In next step, I tried to get contatc name using method getContactName(mContext,number):

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

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

    return contactName;
}

but the method always return null (my incoming call is one of my contacts and its number and number string are exactly the same. I don't know that why this code does not work. I really appreciate any help you can provide.

Mr. Nobody
  • 327
  • 2
  • 8
  • 21

1 Answers1

0

Try adding the permission in Manifest:

<uses-permission android:name="android.permission.READ_CONTACTS"/>
chengsam
  • 7,315
  • 6
  • 30
  • 38
  • Thank you @chengsam. I have added it before. If we don't add this permission, app will be crashed because of security exception. – Mr. Nobody Jul 15 '16 at 15:41
  • You may refer to this [question](http://stackoverflow.com/questions/36700475/getting-null-value-while-retrieving-the-contact-name-from-contact-email) – chengsam Jul 15 '16 at 15:49