Tuesday, 24 June 2014

Android CalledFromWrongThreadException


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.


Use Activity.runOnUiThread()

For instance, within your MainActivity (or whatever your activity class is named):

public void myFunctionCalledByAnotherThread() {
  // ... stuff ...

  runOnUiThread(new Runnable() {
    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( ... )


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.


No comments:

Post a Comment