2014-09-06 41 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; 
}