This error occurs when trying to access UI elements from any thread that is not the UI thread.
To access/modify elements from a non-UI-thread, use runOnUIThread
.
However as you need to change a UI element from within a fragment
, runOnUIThread
should be invoked onto the fragments owning activity. You can do this through getActivity().runOnUIThread()
.
EG:
timer.schedule(new TimerTask() {
@Override
public void run() {
// Your logic here...
// When you need to modify a UI element, do so on the UI thread.
// 'getActivity()' is required as this is being ran from a Fragment.
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
myTextBox.setText("my text");
}
});
}
}, 0, 3000); // End of your timer code.
For further information see the following documentation:
- Android Fragments (specifically, getActivity()).
- TimerTask.
- Invoking a Runnable on the UI thread.