【问题标题】:Get contact image throws NPE获取联系人图片会引发 NPE
【发布时间】:2015-05-22 16:26:52
【问题描述】:

我正在尝试获取联系人的图像,但它总是抛出 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);
    }

【问题讨论】:

  • 投掷哪一行?
  • @eduyayo 在这个Log.d("adapter", u.toString() + " uri"); 上,但所选联系人确实有图片
  • 一个错误的事情是你应该添加一个finally块来关闭光标。但无论如何。您正在搜索的用户返回一个打开的光标,moveToFirst() 返回 true?
  • 检查u.toString(),你是否为空
  • 确实为空。该行中的任何其他内容都不会引发异常。

标签: android uri android-contacts


【解决方案1】:

你能把你的代码改成

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() 正在抛出异常

【讨论】:

    猜你喜欢
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 2014-01-19
    • 2014-01-14
    • 1970-01-01
    相关资源
    最近更新 更多