2010-10-18 89 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) 
{ 
} 
相關問題