Skip to content Skip to sidebar Skip to footer

Getting Null Value While Retrieving The Contact Name From Contact Email

I want to retrieve the contact name from the contact email, so what I have done is as follows from https://stackoverflow.com/a/18064869/5738881. public static String readContacts(

Solution 1:

You should replace

Uriuri= Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(email));
Cursorcursor= cr.query(uri, newString[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);

with

Uriuri= Uri.withAppendedPath(ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(email));
    Cursorcursor= cr.query(uri, newString[]{ContactsContract.CommonDataKinds.Email.CONTACT_ID,
            ContactsContract.Data.DISPLAY_NAME}, null, null, null);

and then test it..

Solution 2:

Always check getCount before use it.

if(cursor!=null && cursor.getCount()>0 )
{
 cursor.moveToFirst();


}else{
   returnnull;
}

Also check whether you have declared permission to read contact in manifest:

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

You'll need a few other related permissions as well, look at the documentation for content to see which.

I suggested to try in this way and also debug your code using break point where is the problem.

publicstaticStringreadContacts(Context context, String email) {
    ContentResolver cr = context.getContentResolver();
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(email));
    Cursor cursor = cr.query(uri, newString[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
    String contactName = null;
    if(cursor!=null && cursor.getCount()>0 )
    {
     cursor.moveToFirst();
     contactName =  cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
    }else{
       returnnull;
    }
    if (!cursor.isClosed()) {
        cursor.close();
    }

    Log.e("....contact name....", email + "\n" + contactName);

    return contactName;

}

Post a Comment for "Getting Null Value While Retrieving The Contact Name From Contact Email"