Android "Only the original thread that created a view hierarchy can touch its views." error in Fragment [duplicate] Android "Only the original thread that created a view hierarchy can touch its views." error in Fragment [duplicate] multithreading multithreading

Android "Only the original thread that created a view hierarchy can touch its views." error in Fragment [duplicate]


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:

  1. Android Fragments (specifically, getActivity()).
  2. TimerTask.
  3. Invoking a Runnable on the UI thread.


you need to use the runOnUIThread() function I have an example somwhere that I will post when I find it.

you need to give your timer an instance of MainActivity alternatively see this question I asked Android image timing issues with what sounds like a similar thing to what you were trying to do

public static void updateText(Activity act, resID){ loadingText = (TextView) activity.findViewById(R.id.loadingScreenTextView);          act.runOnUiThread(new Runnable()                 {                     public void run()                      {                       loadingText.setText(resID);                     }                });}


You are doing UI operation from another thread. I suggest you to use following.

runOnUiThread(new Runnable() {                  @Override                public void run() {                    kiir.setText(ki_adat);                }