Updating Views from non-UI threads
I run your code snippet with sleep
in Lollipop and it crashes. The stack trace is:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6357) at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:909) at android.view.ViewGroup.invalidateChild(ViewGroup.java:4690) at android.view.View.invalidateInternal(View.java:11801) at android.view.View.invalidate(View.java:11765) at android.view.View.invalidate(View.java:11749) at android.widget.TextView.checkForRelayout(TextView.java:6850) at android.widget.TextView.setText(TextView.java:4057) at android.widget.TextView.setText(TextView.java:3915) at android.widget.TextView.setText(TextView.java:3890) at com.test.MainActivity$16.run(MainActivity.java:1126) at java.lang.Thread.run(Thread.java:818)
So the key hides around line 4057 of TextView.setText
which is:
if (mLayout != null) { checkForRelayout();}
We can see if the mLayout
of the TextView
is null
, checkForRelayout()
won't be called and thus the app will not crash. And the mLayout
will be initialized in onDraw
of TextView
. So the app doesn't crash the first time setText
is called because mLayout
is null. After drawing, mLayout
is initialized and cause the app to crash the second time setText
is called.
I guess you start the Thread
before the TextView
is drawn (e.g. in onCreate
or onResume
). Right?
Whether the app crashes or not depends on the TIME you call setText
. If you call setText
before the TextView
is first drawn, everything is ok. Otherwise the app crashes.
Thread is a parallel process to UI thread. when you try to put the sleep function inside a thread, the execution of the thread stops. The answer to your question is inside the question itself. it says - Only the original thread that created a view hierarchy can touch its views. so other are two thread running one ui thread and the other one which you created. when you call the sleep method. your thread stops execution for which there is no synchronization with the ui thread. and when your thread tries to change the text of textview, both the thread are not in sync. before the sleep the thread were in sync. and after sleep they are not in sync,.