Jeff Bic Jeff Bic - 24 days ago 6
Android Question

Error with setText: "Only the original thread .. can touch its views"

When I want to setText to a textView, the application force closes and gives me this error:


android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.


This is a part of my code :

Thread ThreadRecording = new Thread(new Runnable() {
public void run() {
while(recorder)
{
if (body_num = 10)
{
TextView loog = (TextView)findViewById(R.id.textView1);
loog.setText("Total : 10, Thank you");
}
}
}
});
ThreadRecording.start();


There's a button; if the user clicks it, it calls a function to set
body_num = body_num + 1
and the thread checks if body_num == 10

Answer

Only the original thread that created a view hierarchy can touch its views

Because just only with UI (main) thread, are you able to manipulate views. You can use Hanlder to update your views.

There are two main uses for a Handler:

  1. To schedule messages and runnables to be executed as some point in the future; and
  2. To enqueue an action to be performed on a different thread than your own. When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods as before, but from your new thread. The given Runnable or Message will then be scheduled in the Handler's message queue and processed when appropriate."
    -- from "developer.android.com"

Example:

Backgroud thread:

new Thread() {

public void run() {
    while(recorder)
        {
            if (body_num = 10)
            {                
                messageHandler.sendEmptyMessage(0);
            }
        }
   }

}.start();

Your handler which is put in main thread:

private Handler messageHandler = new Handler() {

public void handleMessage(Message msg) {
             //update your view here
   }
};