clicker
clicker

Reputation: 13

my app getting crashed when i use this threads codes

My purpose is simple,I want to creat a countdown that count from 10 to 1.I have tried using countdown given by google but I can't make it as a thread,so I use this way to creat the same function but I had a problem with this code.My app getting crashed when I use this threads code.Please help me man.

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

}



}

Upvotes: 1

Views: 58

Answers (1)

Nick H
Nick H

Reputation: 8992

Your problem isnt with the thread, its with these lines

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

You probably have that textView starting out with some text in the XML("Large Text"). Remove it. "Large Text" isn't a number, so when you call parseInt() on that original string its trying to convert "Large Text" to a number.

Try this code:

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

}

with a try/catch block

Upvotes: 1

Related Questions