我正在使用在这里找到的流行的延迟加载类:http://stackoverflow.com/questions/541966/android-how-do-i-do-a-lazy-load-of-images-in-listview/3068012#3068012
我遇到的问题是,我在多个活动中使用了这个类。在活动之间来回导航(加载图片)最终会导致我的应用程序崩溃,出现以下错误:
12-07 19:54:42.414: W/dalvikvm(1204): threadid=91: thread exiting with uncaught exception (group=0x4001b188)
12-07 19:54:42.424: E/AndroidRuntime(1204): Uncaught handler: thread Thread-47 exiting due to uncaught exception
12-07 19:54:42.434: E/AndroidRuntime(1204): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
12-07 19:54:42.434: E/AndroidRuntime(1204): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
12-07 19:54:42.434: E/AndroidRuntime(1204): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:459)
12-07 19:54:42.434: E/AndroidRuntime(1204): at de.tablayoutexample.ImageLoader.decodeFile(ImageLoader.java:124)
12-07 19:54:42.434: E/AndroidRuntime(1204): at de.tablayoutexample.ImageLoader.getBitmap(ImageLoader.java:78)
12-07 19:54:42.434: E/AndroidRuntime(1204): at de.tablayoutexample.ImageLoader.access$0(ImageLoader.java:73)
12-07 19:54:42.434: E/AndroidRuntime(1204): at de.tablayoutexample.ImageLoader$PhotosLoader.run(ImageLoader.java:182)下面的代码是ImageLoader类的一部分,我怀疑它是罪魁祸首。最初,REQUIRED_SIZE设置为70,这太小了。我将其设置为200,这会使图像质量更好,但会更快地使应用崩溃。
这种延迟加载方法不是应该在用户每次离开活动时都清理图像吗?每次我在另一个活动中加载更多的图片时,它似乎只是在堆积起来。
我是android编程的新手,所以也许有人可以帮我优化这段代码。
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=200;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}发布于 2011-12-08 09:58:56
WeakHashMap可以帮助你缓存位图。http://developer.android.com/reference/java/util/WeakHashMap.html
https://stackoverflow.com/questions/8424876
复制相似问题