2015-12-02 33 views
1

我的目的很簡單,我想創建一個從10到1計數的倒計時。我嘗試使用谷歌給出的倒計時,但我不能使它成爲一個線程,所以我用這種方式來創建相同的功能,但我有這個code.My應用程序崩潰時,我使用這個線程code.Please幫助我的人。我的應用程序崩潰時,我使用此線程代碼

public class MainActivity extends Activity { 
TextView textView; 
Handler handler = new Handler(){ 

    @Override 
    public void handleMessage(Message msg) { 
     // TODO Auto-generated method stub 
     super.handleMessage(msg); 
     String string = textView.getText().toString(); 
     int num = Integer.parseInt(string); 
     num = num-1; 
     string = Integer.toString(num); 
     textView.setText(string); 
    } 

}; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    textView = (TextView) findViewById(R.id.textView); 
} 

@Override 
protected void onStart() { 
    // TODO Auto-generated method stub 
    super.onStart(); 
    Thread myThread = new Thread(new Runnable(){ 

     @Override 
     public void run() { 
      // TODO Auto-generated method stub 
      for(int i = 10; i>0;i--){ 
       try { 
       Thread.sleep(1000); 
       //handler.sendMessage(handler.obtainMessage()); 
       handler.sendMessage(handler.obtainMessage()); 

       } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      } 
     } 
    }); 
    myThread.start(); 

} 



} 
+0

這裏是鏈接我的日誌貓,https://photos.google.com/share/AF1QipO-kaTwmY54c70Mk0K67h9sAwA77qLYjoTxClh2jxpUj9uJGeBczYkhvU_TkInLsw/ photo/AF1QipM0O6Q33D-l0x8We0RWskSk_Tt5iNr5iD84cr8T?key = bWZER2lkTkZoNDNYTjJxLXdsYS1pWFFnMzU1WUZR – clicker

+3

您應該將您的實際logcat消息粘貼到您的帖子中。沒有在評論中添加鏈接 – codeMagic

+0

確定兄弟,我得到10個聲望 – clicker

回答

1

你的心不是問題與線程,與這些線

String string = textView.getText().toString(); 
int num = Integer.parseInt(string); 

你可能有TextView的開始接觸在XML一些文字(「大文本」)。去掉它。 「大文本」不是一個數字,因此當您在該原始字符串上調用parseInt()時,會嘗試將「大文本」轉換爲數字。

試試這個代碼:

try { 
    String string = textView.getText().toString(); 
    int num = Integer.parseInt(string); 
    textView.setText(String.valueOf(--num)); 
catch(NumberFormatException ignored){ 

} 

用try/catch塊

+0

非常感謝你的兄弟,我愛你。你解決了我的問題! – clicker

+0

隨時= p。真高興你做到了。這是一個很酷的小技巧,我發現不久之前將這個命名空間添加到您的佈局XML文件xmlns:tools =「http://schemas.android.com/tools」 現在,如果你想看到文本里面預覽,而不是使用android:text =「Large Text」設置實際文本值使用工具:text =「大文本」。當您構建應用程序時,它實際上不會有值,但它會顯示在預覽中。 –

+0

亞這是很好的信息!讚賞它。我嘗試過它,它的工作原理。 – clicker