0

I have created a Thread in onCreate(). It is running fine. Now I want to change something in view, when the thread is over. But if add it in the run() method, it is giving android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. error. How to solve this problem?

Thread updateThread = new Thread() {
 @Override
 public void run() {
  ................
  ................
   //this line is giving problem
loader.setVisibility(View.INVISIBLE);                               
 }
};
updateThread.start();
antyrat
  • 27,479
  • 9
  • 75
  • 76
dev_android
  • 8,698
  • 22
  • 91
  • 148

2 Answers2

1

You should use an AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html instead of Thread, and do your loader.setVisibility(View.INVISIBLE) inside onPostExecute()

Karl-Bjørnar Øie
  • 5,554
  • 1
  • 24
  • 30
1

In Android, only the original UI-Thread can make changes to it's View. That's security policy. A solution that might be interesting for you, too is shown in this older thread.

Also have a look at Android's Handler-class (which is used in the Thread above).

But (as mentioned by zerpage), an AsyncTask might be the better way.

Community
  • 1
  • 1
Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111