我正在使用这里发现的流行的延迟加载类: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;
}
答案 0 :(得分:0)
WeakHashMap可以帮助你缓存位图。 http://developer.android.com/reference/java/util/WeakHashMap.html