BitmapFactory decodeStream在listview中不起作用

时间:2015-01-24 09:24:40

标签: java android

CustomList.java

public class CustomList extends ArrayAdapter<String> {
    private final Activity context;
    private final ArrayList<String> web;
    private final ArrayList<InputStream> imglist;

    public CustomList(Activity context, ArrayList<String> alist,
            ArrayList<InputStream> bitmapArray) {
        super(context, R.layout.listview_custom, alist);
        this.context = context;
        this.web = alist;
        this.imglist = bitmapArray;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView = inflater.inflate(R.layout.listview_custom, null);

        TextView txtTitle = (TextView) rowView
                .findViewById(R.id.drawer_item_text);

        ImageView imageView = (ImageView) rowView
                .findViewById(R.id.drawer_item_icon);

        txtTitle.setText(web.get(position));

        if (imglist.get(position) != null) {
            imageView.setImageBitmap(BitmapFactory.decodeStream(imglist
                    .get(position)));
        } else {
            imageView.setImageResource(R.drawable.ic_launcher);
        }
        System.out.println("Image Input sream " + imglist.get(position));

        return rowView;
    }
}

自定义适配器

bitmapArray.add(openPhoto(contact_id_long));

CustomList adapter = new CustomList(MainActivity.this, Alist,
                        bitmapArray); 

                list.setAdapter(adapter);
public InputStream openPhoto(long contactId) {
    Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
            contactId);
    Uri photoUri = Uri.withAppendedPath(contactUri,
            Contacts.Photo.CONTENT_DIRECTORY);
    Cursor cursor = getContentResolver().query(photoUri,
            new String[] { Contacts.Photo.PHOTO }, null, null, null);
    if (cursor == null) {
        return null;
    }
    try {
        if (cursor.moveToFirst()) {
            byte[] data = cursor.getBlob(0);
            if (data != null) {
                return new ByteArrayInputStream(data);
            }
        }
    } finally {
        cursor.close();
    }
    return null;
}

自定义arrayadapter,我能够看到文本而不是图像,但是当我签入日志时,InputStream工作正常,如果我在列表视图外使用BitmapFactory.decodeStream,我就能看到图像。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您存储InputStream个对象的列表并从中解码位图。但输入流在使用一次后将返回null。存储路径而不是输入流。 还有标记然后重置输入流(mark()类的reset()InputStream方法)。但我不建议使用它们。我记得有一个关于这种方法使用和位图解码的错误。