0

When I run a code below, application does not fall:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    final Button b = (Button)findViewById(R.id.button1);
    new Mt(b).start();

}

And this code falls (when i click on the button1 with error "CalledFromWrongThreadException"):

@Override
protected void onCreate(Bundle savedInstanceState) {
    ....
    final Button b = (Button)findViewById(R.id.button1);
    b.setOnClickListener(new Button.OnClickListener() {         
            @Override
            public void onClick(View v) {
                new Mt(b).start();
            }
        });

} 

Where Mt class is

class Mt extends Thread{
    Button b;
    Mt(Button b){
        this.b=b;
    }
    @Override
    public void run() {
        b.setText("4");
    }
}

Why the first example does not fall with error "CalledFromWrongThreadException" ?

dr_yand
  • 171
  • 2
  • 11

2 Answers2

0

Thread will run in non UI Thread. UI related operations must be done in UI thread.. Modify the code in thread.run() method

public void run() {
    runOnUiThread(new Runnable() {

       @Override
       public void run() {
       // TODO Auto-generated method stub
           b.setText("4");  
       }
   });

}
Jagadesh Seeram
  • 2,630
  • 1
  • 16
  • 29
0

This is just a hunch, but the first example does not fail because there is no UI during the execution of onCreate. The check for thread access does not occur in the setText method until it actually plans on changing something that is visible to the user. Since nothing is being drawn to the screen yet, there is no problem.

Dave
  • 4,282
  • 2
  • 19
  • 24