How do I display a contact's photo from the co

2020-05-01 02:25发布

问题:

This code (within my CustomAdapter class) displays only the contact id based on the who sent me text messages and puts them into an ArrayList, then displays the list.

I have a ImageView called holder.photo next to each contact id. How would I go about displaying the contact's photo in the in the ImageView?

        String folder = "content://sms/inbox/";
        Uri mSmsQueryUri = Uri.parse(folder);
        messages = new ArrayList<String>();
        contactID = new ArrayList<String>();
        SMS = new ArrayList<String>();

        try {
            c = context.getContentResolver().query(mSmsQueryUri,
                    new String[] { "_id", "address", "date", "body" },
                    null, null, null);
            if (c == null) {
                Log.i(TAG, "cursor is null. uri: " + mSmsQueryUri);
            }

        } catch (Exception e) {
            //Log.e(TAG, e.getMessage());
        } finally {
            c.close();
        }
            c.moveToFirst();
            while (c.moveToNext()) {

                phoneNumber = c.getString(0);
                contactID.add(phoneNumber);
            }
        holder.photo.?????
        //contact will cycle through all names and display each in a listview.
        holder.contact.setText(contactID.get(position);

Currently, my listview displays this:

  • android_icon-----John Doe
  • android_icon-----Jane Smith
  • android_icon-----Foo Barr

回答1:

try this..

public void getContacts(ContentResolver cr) {
    Cursor phones = cr.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
            null, null);
    while (phones.moveToNext()) {
        String name = phones
                .getString(phones
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String contactId = phones
                .getString(phones
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));

       Bitmap bitmap = loadContactPhoto(
                getContentResolver(), Long.valueOf(contactId))
       }
    phones.close();

get Bitmap image

public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
    Uri uri = ContentUris.withAppendedId(
            ContactsContract.Contacts.CONTENT_URI, id);
    InputStream input = ContactsContract.Contacts
            .openContactPhotoInputStream(cr, uri);
    if (input == null) {
        return null;
    }
    return BitmapFactory.decodeStream(input);
}