使用Volley的磁盘缓存时出现内存不足问题

7
在我的Android应用程序中,我使用Volley在自定义Listview中加载图像。当我多次刷新(删除所有项目并加载项目)列表视图时,我的应用程序会崩溃并显示错误信息。你如何解决这个问题?
04-26 13:08:01.038: E/dalvikvm-heap(18040): 在分配1684947261字节内存时出现内存不足错误。 04-26 13:08:01.048: W/dalvikvm(18040): 线程299退出时未捕获的异常 (group=0x41745da0) 04-26 13:08:01.048: E/AndroidRuntime(18040): 致命异常: Thread-11094 04-26 13:08:01.048: E/AndroidRuntime(18040): 进程:com.android.myapp,PID:18040 04-26 13:08:01.048: E/AndroidRuntime(18040): java.lang.OutOfMemoryError(内存不足) 在com.android.volley.toolbox.DiskBasedCache.streamToBytes(DiskBasedCache.java:316)处

有解决办法吗? - CQM
1
这个问题已经存在了将近两年,但我仍在寻找解决方案。这个问题类似,但答案对我不起作用。楼主你最终解决了吗? - yuval
2个回答

1
你尝试过吗?
RequestQueue volleyQueue = Volley.newRequestQueue(this);
DiskBasedCache cache = new DiskBasedCache(getCacheDir(), 16 * 1024 * 1024);
volleyQueue = new RequestQueue(cache, new BasicNetwork(new HurlStack()));
volleyQueue.start();

https://dev59.com/6Xvaa4cB1Zd3GeqPF6IU#21299261

这将更改缓存大小。

1
我遇到了一个类似的问题,即在ListView中加载图像时出现了问题。看起来您需要自己处理缓存。下面是我的实现方式,我放在了adapter的public View getView(int position, View convertView, ViewGroup parent)方法中:
Bitmap cachedBitmap = imageCache.getBitmap(item.getPhotoUrl());
if (cachedBitmap != null)
{
    holder.photo.setImageBitmap(cachedBitmap);
}
else {
    ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(this.context), imageCache);
    imageLoader.get(item.getPhotoUrl(), new ImageLoader.ImageListener() {
        @Override
        public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
            if (item.getPhotoUrl() != null && response.getBitmap() != null)
                imageCache.putBitmap(item.getPhotoUrl(), response.getBitmap());
        }

        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });

    //This is a custom imageview, you can create your own implementation for loading the image url to the imageview
    holder.photo.setImageUrl(item.getPhotoUrl(), imageLoader);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接