goddess1875
goddess1875

Reputation: 103

How android update ui

Android recommend update ui in the ui thread,but i found that i can update the ui in the non-ui thread directly like below:

public class MainActivity extends Activity {
private TextView textView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView) findViewById(R.id.text);
    new Thread(new Runnable() {
        @Override
        public void run() {
            textView.setText("SecondThread");
        }
    }).start();
}

} That's run correctly,but if i sleep the thread 1000ms:

public class MainActivity extends Activity {
private TextView textView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView) findViewById(R.id.text);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                **Thread.sleep(1000);**
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            textView.setText("SecondThread");
        }
    }).start();
}

} I get the error"Only the original thread that created a view hierarchy can touch its views",i try to change the sleep value much times,i found when i set the value 135 or less,it can run correctly: Thread.sleep(135);

Thread.sleep(134);

Thread.sleep(...); That's very interesting!But why it happen?I can't find any way to make sense of that,is anyone can help me?thanks!

Upvotes: 2

Views: 208

Answers (2)

SorryForMyEnglish
SorryForMyEnglish

Reputation: 1181

so will always work

new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                **Thread.sleep(1000);**
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runOnUiThread(new Runable(){
               @Override
               public void run(){
               textView.setText("SecondThread");
            });

        }
    }).start();

There is another way to use the Handler()

Upvotes: 0

Chaosit
Chaosit

Reputation: 1116

If you are trying to touch views from background thread you should consider using runOnUiThread method, which accepts runnable as argument in which you can update views

EDIT: Also I would recommed you to use AsyncTask to achieve your goals, it has two callbacks onPreExecute and onPostExecute, whiche are invoked on the UI thread

Upvotes: 1

Related Questions