为列表视图缓存图片

时间:2011-09-23 05:34:02

标签: android caching listview memory-management adapter

所以我有一个包含来自某些网址的图片的列表视图,我尝试在加载到位图的数组列表后保存图片,但最后只有2-3个图片显示在我的设备列表中(模拟器显示所有图片) ,所以我试着在下载后缓存图片,我使用: `

     for (int i = 0; i < url.length; i++){
            URL urlAdress = new URL(url[i]);
            HttpURLConnection conn = (HttpURLConnection) urlAdress
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            Bitmap bmImg = BitmapFactory.decodeStream(is);

            // picList.add(bmImg);

            File cacheDir = context.getCacheDir();
            File f = new File(cacheDir, "000" + (i + 1));
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(f);
                bmImg.compress(Bitmap.CompressFormat.JPEG, 80, out);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null)
                        out.close();
                } catch (Exception ex) {
                }
            }
        }

` 将图片保存在缓存中,然后我用它来加载适配器中缓存的图片:

File cacheDir = context.getCacheDir();
    File f = new File(cacheDir, "000" + position);
    Drawable d = Drawable.createFromPath(f.getAbsolutePath());
    holder.icon.setImageDrawable(d);

但我仍然从9开始拍3-4张照片,这是一个记忆问题吗? (所有照片一起有300 kb)

2 个答案:

答案 0 :(得分:0)

为什么要创建自己的,因为懒惰列表已经完成了这项工作,请参阅Lazy load of images in ListView

答案 1 :(得分:0)

发现问题Bitmap bmImg = BitmapFactory.decodeStream(is);有错误并跳过慢速网络连接上的数据,就像在真实设备上一样,所以我添加了

Bitmap bmImg = BitmapFactory.decodeStream(new FlushedInputStream(is));

static class FlushedInputStream extends FilterInputStream {
    public FlushedInputStream(InputStream inputStream) {
        super(inputStream);
    }

    @Override
    public long skip(long n) throws IOException {
        long totalBytesSkipped = 0L;
        while (totalBytesSkipped < n) {
            long bytesSkipped = in.skip(n - totalBytesSkipped);
            if (bytesSkipped == 0L) {
                int b = read();
                if (b < 0) {
                    break; // reached EOF
                } else {
                    bytesSkipped = 1; // read one byte
                }
            }
            totalBytesSkipped += bytesSkipped;
        }
        return totalBytesSkipped;
    }
}