Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

java - Android Thread modify EditText

I am having a problem with modifying EditText in another function started by the thread:

Thread thRead = new Thread( new Runnable(){
    public void run(){
       EditText _txtArea = (EditText) findViewById(R.id.txtArea);
       startReading(_txtArea);
    }
 });

my function is as follows:

public void startReading(EditText _txtArea){
         _txtArea.setText("Changed");
}

It always force closes while trying to modify the edittext. Does someone know why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UI views should not be modified from non-UI thread. The only thread that can touch UI views is the "main" or "UI" thread, the one that calls onCreate(), onStop() and other similar component lifecycle function.

So, whenever your application tries to modify UI Views from non-UI thread, Android throws an early exception to warn you that this is not allowed. That's because UI is not thread-safe, and such an early warning is actually a great feature.


UPDATE:

You can use Activity.runOnUiThread() to update UI. Or use AsyncTask. But since in your case you need to continuously read data from Bluetooth, AsyncTask should not be used.

Here is an example for runOnUiThread():

runOnUiThread(new Runnable() {            
    @Override
    public void run() {
        //this will run on UI thread, so its safe to modify UI views.
         _txtArea.setText("Changed");
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...