Problem:
When I try to run functions such as myView.setText(myText), I get something similar to the following error: CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Solution:
For instance, within your MainActivity (or whatever your activity class is named):
public void myFunctionCalledByAnotherThread() {
// ... stuff ...
runOnUiThread(new Runnable() {
@Override
public void run() {
// ... code to modify ui such as View.setText() ...
}
});
// ... other stuff ...
}
If you're outside of the Activity, you can also try getActivity():
getActivity().runOnUiThread( ... )
Explanation:
This error is caused by a thread other than the original thread that created the UI element/View, attempting to modify that view. An example of something that will cause this error is placing a setText() call into the run() function of a java TimerTask.
References:
- http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29
- http://developer.android.com/reference/android/app/Fragment.html#getActivity%28%29
- http://stackoverflow.com/questions/5161951/android-only-the-original-thread-that-created-a-view-hierarchy-can-touch-its-vi
No comments:
Post a Comment