取联系人按号码显示图片

时间:2012-08-14 10:30:30

标签: android android-contentprovider

我正在使用Android应用。在我的应用中,我必须显示联系人显示名称和displaypic。为了按编号获取联系人displayname,我使用以下代码。

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

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

    try {
        if (contactLookup != null && contactLookup.getCount() > 0) {
            contactLookup.moveToNext();
            name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));

            //String contactId = contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
        }
    } finally {
        if (contactLookup != null) {
            contactLookup.close();
        }
    }

    return name;
}

它的工作正常。请帮我联系displaypic这样的。

1 个答案:

答案 0 :(得分:1)

以下代码适用于我。

public Drawable getContactDisplaypicByNumber(String number) {
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));

    String contactId = null;
    InputStream input = null;
    String[] projection = new String[] {
            ContactsContract.PhoneLookup.DISPLAY_NAME,
            ContactsContract.PhoneLookup._ID};
        Drawable d=null;

    ContentResolver contentResolver = getContentResolver();
    Cursor contactLookup = contentResolver.query(uri,projection, null, null, null);


    if (contactLookup.moveToFirst()) {
        contactId = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.PhoneLookup._ID));

        Uri uri1 = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId));
        input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri1);


    }
    else {

        Log.v("ffnet", "Started uploadcontactphoto: Contact Not Found @ " + number);

        return d; // contact not found

    }

    if (input == null) {
        Log.v("ffnet", "Started uploadcontactphoto: No photo found, id = " + contactId + " name = " + name);
        d=getResources().getDrawable(R.drawable.ic_launcher);
        return d; // no photo
    } else {

        Log.v("ffnet", "Started uploadcontactphoto: Photo found, id = " + contactId + " name = " + name);
        d=Drawable.createFromStream(input, "");
        System.out.println("ddddddddddddddddddddddddddddddddd"+d);
        return d;
    }

}