我一直對我的應用程序有很多內存問題。我試圖捕獲內存異常,然後使用吐司說內存不足來顯示一條消息。當我嘗試顯示吐司消息時崩潰,但不會在調試器中崩潰
當我運行該應用程序與它的代碼崩潰。當我在調試器中運行它時,不會崩潰,但不會出現消息。
我試圖在Activty類的onCreate方法內的catch內存異常中顯示消息。
代碼塊:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set size of card image
ImageView CardImage = (ImageView)findViewById(R.id.viewcard);
int ScreenWidth=getWindowManager().getDefaultDisplay().getWidth();
int ScreenHeight=getWindowManager().getDefaultDisplay().getHeight();
// fix for tblets
if (ScreenHeight<ScreenWidth)
ScreenWidth=ScreenHeight;
int CardWidth=ScreenWidth/2;
CardWidth+=CardWidth/10;
// set bitmap
// Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.card2);
String FileName=new String("card");
FileName+=Integer.toString(CardId+1);
FileName+=".jpg";
// put in text that matches card
TextView mCardText = (TextView)findViewById(R.id.cardtext);
mCardText.setText("Card Meaning \n"+ cCardText.mCardMeaning[ CardId]);
// put in text that matches card
TextView mHouseText = (TextView)findViewById(R.id.housetext);
mHouseText.setText("House Meaning \n"+ cCardText.mHouseMeaning[ HouseId-1]);
try {
AssetManager assetManager= getAssets();
InputStream inputStream;
inputStream=assetManager.open(FileName);
Bitmap icon=BitmapFactory.decodeStream(inputStream);
CardImage.setImageBitmap(icon);
} catch(OutOfMemoryError e)
{
/////////////////////////////////////////////////////////////////////
// crashes heare
Context context = getApplicationContext();
CharSequence text = "Out of Memory ";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
gi++;
return;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
//scale it
// note: only code here that pertains to card image, becouse if card image cannot be loaded
// the above exceptions will go off and we will never get here
CardImage.getLayoutParams().width=CardWidth;
CardImage.getLayoutParams().height = (int)((float) CardWidth *1.7);
}
你可以從logcat發佈StackTrace嗎? –
活動擴展上下文這意味着,而不是'context = getApplicationContext()',你可以簡單地在你的catch塊中使用'this'。 – WarrenFaith