Tuesday, 24 June 2014

Android CalledFromWrongThreadException

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:

Use Activity.runOnUiThread()

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:

No comments:

Post a Comment