2014-09-06 34 views
0

當用戶對一些行動,但有些時候它給錯誤,如如何克服從我的Android應用程序OutOfMemory錯誤?

java.lang.OutOfMemoryError: bitmap size exceeds VM budget

,我使用在MainActivity下面的方法來設置位圖我創建它加載六個位圖作爲按鈕的背景改變按鈕狀態的應用:

  on_duty.setBackgroundDrawable(GetApplicationDrawable 
        .Button3(R.drawable.on_duty_d)); 
      off_duty.setBackgroundDrawable(GetApplicationDrawable 
        .Button3(R.drawable.off_duty)); 
      journey_start.setBackgroundDrawable(GetApplicationDrawable 
        .Button3(R.drawable.journey)); 
      journey_end.setBackgroundDrawable(GetApplicationDrawable 
        .Button3(R.drawable.destination_d)); 
      metting_in.setBackgroundDrawable(GetApplicationDrawable 
        .Button3(R.drawable.meeting)); 
      metting_out.setBackgroundDrawable(GetApplicationDrawable 
        .Button3(R.drawable.over_d)); 

我的我的GetApplicationDrawable類內部將Button3方法類似波紋解碼位圖

public static Drawable Button3(int res_id) { 
    Bitmap bitmap = null; 
    try { 
     bitmap = BitmapFactory.decodeResource(context.getResources(), 
       res_id); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    int width = bitmap.getWidth(); 
    int height = bitmap.getHeight(); 
    float newWidth = (float) ((float) wt/3); 
    float scaleWidth = ((float) newWidth)/width; 
    float newHeight = (float) ((float) wt/4); 
    float scaleHeight = ((float) newHeight)/height; 
    Matrix matrix = new Matrix(); 
    matrix.postScale(scaleWidth, scaleHeight); 
    Bitmap mannagedBitmap = bitmapMannagement(context.getResources(), 
      res_id, width, height); 
    Bitmap resizedBitmap = Bitmap.createScaledBitmap(mannagedBitmap, 
      (int) newWidth, (int) newHeight, true); 
    Drawable d = new BitmapDrawable(context.getResources(), resizedBitmap); 
    return d; 
} 

謝謝。

+0

Eeek,爲什麼是靜態的?大寫?我建議你使用較小的位圖 - 它們有多大? - 清理不必要的靜態代碼。 – 323go 2014-09-06 04:46:59

+0

我已刪除靜態和問題保持不變。 – 2014-09-06 04:55:53

回答

0

當此代碼失敗時,您需要離開函數或正常處理它。

try { 
    bitmap = BitmapFactory.decodeResource(context.getResources(), 
      res_id); 

} catch (Exception e) { 
    e.printStackTrace(); 
    // here you need to get out of the function 
    // or recover gracefully 
    //TODO set the bitmap to a default bitmap. 
    //TODO or return a null; 
} 
相關問題