当我尝试显示吐司消息时崩溃,但不会在调试器中崩溃

问题描述:

我一直对我的应用程序有很多内存问题。我试图捕获内存异常,然后使用吐司说内存不足来显示一条消息。当我尝试显示吐司消息时崩溃,但不会在调试器中崩溃

当我运行该应用程序与它的代码崩溃。当我在调试器中运行它时,不会崩溃,但不会出现消息。

我试图在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); 


    } 
+0

你可以从logcat发布StackTrace吗? –

+0

活动扩展上下文这意味着,而不是'context = getApplicationContext()',你可以简单地在你的catch块中使用'this'。 – WarrenFaith

当你的内存溢出,所有的赌注都差不多了,因为在这一点上JVM不能真正分配的新内存。所以由于这个原因可能会崩溃。

您可能想要在显示消息之前尝试清除一些指针......但我从未见过任何人实际尝试捕获OutOfMemory错误。

在这篇文章Is it possible to catch out of memory exception in java?下面的第三个答案解释了一下为什么尝试捕捉内存异常是一个非常糟糕的主意。

+0

尝试捕捉低内存广播,然后显示敬酒。糟糕!不是真的抓住。接收。 –