2014-02-15 54 views
0

当我举杯祝酒时,应用程序崩溃,但我不明白为什么。这是代码:eclipse中的吐司错误

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    mvc = (Button) findViewById(R.id.button1); 

    mvc.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      Toast.makeText(getApplicationContext(),"START!" ,Toast.LENGTH_SHORT).show(); 
      new Thread(new Runnable() { 
       public void run() { 
        long startTime = System.currentTimeMillis(); 
        while(startTime + 5000 > System.currentTimeMillis()) 
        { 
      //  } 
      //  while (progressStatus < 1000) { 

         if (k > progressStatus){ 
          progressStatus = k; 
         } 
         else { 
          progressStatus = progressStatus; 
         } 
         // Update the progress bar and display the current value in the text view 
         handler.post(new Runnable() { 
          public void run() { 
           progressBar.setProgress(progressStatus); 

          } 
         }); 
         try { 
          // Sleep for 10 milliseconds. Just to display the progress slowly 
          Thread.sleep(10); 
         } catch (InterruptedException e) { 
          e.printStackTrace(); 
         } 
        } 
        Toast mioToast = Toast.makeText(BluetoothChat.this, 
          "STOP!", 
          Toast.LENGTH_LONG); 

          mioToast.show(); 

       } 

      }).start(); 

     } 

    }); 

第一个敬酒执行它完美,但在第二个,有单词“停止”,应用程序崩溃。怎么会这样? 谢谢。

回答

1

你试图显示在后台线程Toast。 UI只能从UI线程修改,这就是你的应用崩溃的原因。

使用这个代替:

handler.post(new Runnable() { 
    public void run() { 
     Toast.makeText(BluetoothChat.this, 
         "STOP!", 
         Toast.LENGTH_LONG).show(); 
    } 
}; 

这将在UI线程上运行,因而不会崩溃的应用程序。

+0

完美!谢谢! – user3313188

+0

不客气!请点击左边的复选标记来接受此答案。 –

0

试图取代“getApplicationContext()”和“这个”或“your_class_name.this”

+0

不能这样工作 – user3313188