拉动联系人的图片不起作用

时间:2018-04-06 17:17:21

标签: java android android-contacts

我是Call Manager的开发者。我在为我的应用添加一些新功能时遇到了一些困难。

目前,当添加新呼叫(或编辑现有呼叫)时,用户可以从他们自己的联系人列表中选择联系人,并且姓名和电话号码将填充相应的字段。我现在正在尝试检索联系人的照片,但它无法正常工作。我查看了很多帖子,但没有任何工作。

检索联系信息的当前代码是:

// Retrieve the contact data and set name and number to the appropriate fields
private void contactPicked(Intent data){

    ContentResolver cr = getContentResolver();
    Uri uri = data.getData();
    Cursor cur = cr.query(uri, null, null, null, null);
    cur.moveToFirst();

    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
    String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
    nameField.setText(name);
    String number = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    numField.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
    numField.setText(number);
    numField.addTextChangedListener(new PhoneNumberFormattingTextWatcher());;
}

这可以按预期工作。

目前的新代码如下所示:

// Retrieve the contact data and set name and number to the appropriate fields
private void contactPicked(Intent data){

    ContentResolver cr = getContentResolver();
    Uri uri = data.getData();
    Cursor cur = cr.query(uri, null, null, null, null);
    cur.moveToFirst();

    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
    String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
    nameField.setText(name);
    String number = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

    InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri, true);
    BufferedInputStream buf = new BufferedInputStream(photo_stream);
    Bitmap my_btmp = BitmapFactory.decodeStream(buf);
    try {
        buf.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    numField.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
    numField.setText(number);
    numField.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

    Drawable photo = new BitmapDrawable(getResources(), my_btmp);
    contactPhoto.setBackground(photo);
}

如果有人能帮我解决这个问题,我会非常感激。请随时在GitHub repo进一步检查代码,以获得进一步说明。谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个:

Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, id); // create a plain contactUri from the _ID, instead of using the uri given by Intent data
InputStream input = getContentResolver().openInputStream(contactUri)
Bitmap bmp = null;
if (input != null) {
    bmp = BitmapFactory.decodeStream(input);
    input.close();
    BitmapDrawable drawable = new BitmapDrawable(getResources(), bmp);
    contactPhoto.setBackgroundDrawable(drawable);
} else {
    // clear any existing background here if needed
}