简体   繁体   中英

Set TextView value inside a thread in android

I am getting a crash under the fllowing circumstances. I am running a thread in the following way:

Thread t = new Thread(){
    public void run() {    
            text.setText("hello");    
    }
};
t.start;

The crash occurs if I try to set the value of a TextView in my xml, (the reference to text is already available).

Am I doing something fundamentally wrong? Kindly point out where am going wrong.

You can only access user interface components from the UI thread.

Android has a few things to make this easy, such as the method runOnUiThread and the class AsyncTask .

For more reading see Painless Threading and Processes and Threads in the Android documentation.

You should access android ui toolkit widgets only on the UI thread. Read http://developer.android.com/resources/articles/painless-threading.html .

use Handler class and check it for more relevant methods

Handler mHandler;
 mHandler=new Handler(){
hdandleMessage(Message what){

text.setText("hello");

}

};
Thread t = new Thread(){
    public void run()
    {

           mHandler.sendEmptyMessage(int what)

        }
};
t.start;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM