我有一个listview,可能无限滚动加载无限项.
列表视图中的每个项目都有一个或两个我懒得加载的图像.
一切都很好但是当我滚动很长时间它会在log cat中崩溃
08-07 15:26:25.231: E/AndroidRuntime(30979): FATAL EXCEPTION: Thread-60
08-07 15:26:25.231: E/AndroidRuntime(30979): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
08-07 15:26:25.231: E/AndroidRuntime(30979): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
08-07 15:26:25.231: E/AndroidRuntime(30979): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:493)
08-07 15:26:25.231: E/AndroidRuntime(30979): at com.test.android.helper.LazyImageLoader.decodeFile(LazyImageLoader.java:171)
08-07 15:26:25.231: E/AndroidRuntime(30979): at com.test.android.helper.LazyImageLoader.getBitmap(LazyImageLoader.java:112)
08-07 15:26:25.231: E/AndroidRuntime(30979): at com.test.android.helper.LazyImageLoader.access$2(LazyImageLoader.java:106)
08-07 15:26:25.231: E/AndroidRuntime(30979): at com.test.android.helper.LazyImageLoader$ImageLoader.run(LazyImageLoader.java:197)
在我的懒惰图像加载器中,我将位图存储在WeakHashMap中.垃圾收集器应该收集位图吗?
我懒惰的图像加载器就是这样的.
我用我的适配器调用displayImage()和url以及对imageview的引用
public void displayImage(String url, ImageView imageView, int defaultImageResourceId){
latestImageMetaData.put(imageView, url);
if(weakhashmapcache.containsKey(url)){
imageView.setImageBitmap(weakhashmapcache.get(url));
}
else{
enqueueImage(url, imageView, defaultImageResourceId);
imageView.setImageResource(defaultImageResourceId);
}
}
因此,如果我在缓存中找到图像,我会直接设置它,否则我会使用函数enqueueImage()对其进行排队.
private void enqueueImage(String url,ImageView imageView,int defaultImageResourceId){
Image image = new Image(url,imageView,defaultImageResourceId);
downloadqueue.add(图像);
// downloadQueue是一个阻塞队列,等待添加图像
//如果队列即将变满,则删除队列中前面的元素,因为它们无论如何都是不可见的
Iterator iterator = downloadQueue.iterator();
while(iterator.hasNext()&& downloadQueue.remainingCapacity()< 80){
downloadQueue.remove(iterator.next());
}
}
And my image loader thread is this -
class ImageLoader extends Thread {
public void run() {
Image firstImageInQueue;
try {
while((firstImageInQueue = downloadQueue.take()) != SHUTDOWN_TOKEN)
{
Bitmap imageBitmap = getBitmap(firstImageInQueue.url);
if(imageBitmap != null){
weakhashmap.put(firstImageInQueue.url, imageBitmap);
BitmapDisplayer displayer = new BitmapDisplayer(imageBitmap, firstImageInQueue.imageView, firstImageInQueue.url, firstImageInQueue.defaultImageResourceId);
Activity activity = (Activity)firstImageInQueue.imageView.getContext();
activity.runOnUiThread(displayer);
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
finally {
imageLoaderTerminated = true;
}
}
}
getBitmap()只是从url scale中提取图像并将其解码为Bitmap对象. BitmapDisplayer只是一个Runnable,它在UI线程上进行image到imageview的设置.
我究竟做错了什么?