【问题标题】:Cacheing pictures for a listview缓存列表视图的图片
【发布时间】:2011-11-23 09:25:27
【问题描述】:

所以我有一个包含来自某些 url 的图像的列表视图,我尝试在加载位图的 arrayList 后保存图片,但最后我的设备上的列表中只显示了 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)

【问题讨论】:

标签: android caching listview memory-management adapter


【解决方案1】:

发现问题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;
    }
}

【讨论】:

    猜你喜欢
    • 2018-04-18
    • 1970-01-01
    • 2012-07-02
    • 2012-10-22
    • 2012-05-22
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 2014-12-23
    相关资源
    最近更新 更多