How to get a contact image using a phone number in android?

While working with Android Contact ContentProvider. We have a Phone Number and we need to get the URI of the Photo of the contact associated with this phone number

 

With the below code we can get the Contact iMage from Phone Number

String imnage;
    Cursor phonesCursor;


try {
    Uri phoneUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode("Pass here phone number"));
    phonesCursor = getContentResolver().query(phoneUri, new String[]{ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI}, null, null, null);
} catch (NullPointerException e) {
    e.printStackTrace();
}
catch (IllegalArgumentException e){
    e.printStackTrace();
}
if (phonesCursor != null && phonesCursor.moveToFirst()) {
    imnage = phonesCursor.getString(0);

    try {
        img_profile.setImageURI(Uri.parse(imnage));
       
    }catch (NullPointerException e){
        e.printStackTrace();
    }
    // displayName = phonesCursor.getString(0); // this is the contact name
} else {
    Log.e("no contact ", "============");
}
 

 

With the below code we can get the Name of the Contact

 

String str2 = null;
Cursor query = getContentResolver().query(Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(str)), new String[]{"display_name"}, null, null, null);
if (query != null) {
    if (query.moveToFirst()) {
        str2 = query.getString(query.getColumnIndex("display_name"));
    }
    if (query != null && !query.isClosed()) {
        query.close();
    }
}