【问题标题】:my app getting crashed when i use this threads codes当我使用此线程代码时,我的应用程序崩溃了
【发布时间】:2016-03-07 04:20:06
【问题描述】:

我的目的很简单,我想创建一个从 10 到 1 的倒计时。我尝试使用 google 提供的倒计时,但我无法将其作为线程,所以我使用这种方式来创建相同的功能但我遇到了这个代码的问题。当我使用这个线程代码时,我的应用程序崩溃了。请帮帮我。

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();

}



}

【问题讨论】:

  • 这里是我的 Log-cat 的链接,photos.google.com/share/…
  • 您应该将实际的 logcat 消息粘贴到您的帖子中。不要在评论中添加指向照片的链接
  • 好的兄弟,等我获得10个声望
  • 兄弟,您不需要任何特殊的代表数量即可使用标签下方的编辑按钮并像使用代码一样在帖子中复制/粘贴 logcat 输出。

标签: java android multithreading button android-studio


【解决方案1】:

您的问题不在于线程,而在于这些行

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

您可能从 XML(“大文本”)中的一些文本开始使用 textView。去掉它。 “大文本”不是数字,因此当您在该原始字符串上调用 parseInt() 时,它会尝试将“大文本”转换为数字。

试试这个代码:

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

}

带有 try/catch 块

【讨论】:

  • 非常感谢兄弟,我爱你。你解决了我的问题!
  • 随时=p。真高兴你做到了。这是我不久前发现的一个很酷的小技巧.. 将此命名空间添加到您的布局 XML 文件中, xmlns:tools="schemas.android.com/tools" 现在,如果您想在预览中查看文本,而不是设置实际的文本值使用 android:text="Large Text" 使用工具:text="Large Text"。当您构建您的应用程序时,它实际上不会有值,但它会显示在预览中。
  • 是个好信息!很感激。我试过了,效果很好。
猜你喜欢
  • 2020-02-07
  • 1970-01-01
  • 1970-01-01
  • 2022-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多