2010-10-18 53 views
7

所以我有一个懒惰的图像加载器为我的ListView。我也使用this tutorial进行更好的内存管理,并且SoftReference位图图像存储在我的ArrayList中。java.lang.OutOfMemoryError:位图大小超过VM预算

我的ListView工程从数据库加载8个图像,然后一旦用户滚动到底部,它加载另一个8等等等等。当大约35个图像或更少,但更多和我的应用程序没有问题强制关闭OutOfMemoryError

,我不能理解的是我有一个尝试catch在我的代码的东西:

try 
{ 
    BitmapFactory.Options o = new BitmapFactory.Options(); 
    o.inJustDecodeBounds = true; 
    BitmapFactory.decodeByteArray(image, 0, image.length, o); 

    //Find the correct scale value. It should be the power of 2. 
    int width_tmp = o.outWidth, height_tmp = o.outHeight; 
    int scale = 1; 

    while(true) 
    { 
     if(width_tmp/2 < imageWidth || height_tmp/2 < imageHeight) 
     { 
      break; 
     } 

     width_tmp/=2; 
     height_tmp/=2; 
     scale++; 
    } 

    //Decode with inSampleSize 
    BitmapFactory.Options o2 = new BitmapFactory.Options(); 
    o2.inSampleSize = scale; 
    bitmapImage = BitmapFactory.decodeByteArray(image, 0, image.length, o2);   
} 
catch (Exception e) 
{ 
    e.printStackTrace(); 
} 

但try catch块未捕获的OutOfMemory例外,从我了解的SoftReference位图图像应用程序在内存不足时会被清除,从而停止抛出异常。

我在这里做错了什么?

回答

4

OutOfMemoryError是一个错误不是例外,你不应该抓住它。

http://mindprod.com/jgloss/exception.html

编辑:已知的问题看this issue

+0

啊,我的坏......根本不知道。有什么我可以做,以防止它发生?我完全被卡住了。 – mlevit 2010-10-18 05:11:26

+0

如果有办法解决问题,或者如果想通过例如在单独的过程中开始新活动来告诉用户,则捕获OutOfMemoryError是非常有意义的。 – arberg 2010-12-07 12:36:31

9

我想可能是这个职位将帮助你

//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); 

     //The new size we want to scale to 
     final int REQUIRED_SIZE=70; 

     //Find the correct scale value. It should be the power of 2. 
     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

+1非常有帮助的解决方案。适用于我。 Thanx – 2011-09-19 10:55:52

+0

+1这个例子也适用于我。谢谢! – ScratchMyTail 2011-11-03 19:07:36

+0

应该是选择解决方案! – Pascal 2013-01-28 16:37:20

0

错误和异常是从Throwable的子类。 错误应该是如此激烈,你不应该抓住他们。

但你可以捕捉任何东西。

try 
{ 
} 
catch (Throwable throwable) 
{ 
} 
相关问题