获取联系人图像会引发NPE

时间:2015-03-19 13:58:40

标签: android uri android-contacts

我试图获取联系人的图像,但它总是抛出NPE。有人能告诉我出了什么问题吗?

这是我的代码:

Uri u = getPhotoUri(data.get(position).getContactID());
            Log.d("adapter", u.toString() + " uri");
            if (u != null) {
                holder.image.setImageURI(u);
            } else {
                holder.image.setImageResource(R.mipmap.ic_launcher);
            }

和方法:

private Uri getPhotoUri(String ID) {
        try {
            Cursor cur = activity.getContentResolver().query(
                    ContactsContract.Data.CONTENT_URI,
                    null,
                    ContactsContract.Data.CONTACT_ID + "=" + ID + " AND "
                            + ContactsContract.Data.MIMETYPE + "='"
                            + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
                    null);
            if (cur != null) {
                if (!cur.moveToFirst()) {
                    return null; // no photo
                }
            } else {
                return null; // error in cursor process
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long
                .parseLong(ID));
        return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
    }

1 个答案:

答案 0 :(得分:0)

您可以将代码更改为

Uri u = getPhotoUri(data.get(position).getContactID());

            if (u != null) {
            Log.d("adapter", u.toString() + " uri");
                holder.image.setImageURI(u);
            } else {
                holder.image.setImageResource(R.mipmap.ic_launcher);
            }

似乎u.toString()正在抛出异常