0

When I first started my project, I updated the UI from all over the place. This worked for a while, because only a Seekbar was being updated from a worker thread and for some reason that worked. I then updated a TextView from the same worker thread and it crashed my app, so I started calling runOnUIThread(new Runnable(){...}); every time I needed to update the UI from a worker thread.

My Fragments also need to update the UI and they update their own UI elements as well as the Activity elements with no errors.

Should I be using runOnUIThread(new Runnable(){...}); in Fragments to update UI elements or are the Fragments on the UI thread?

John Glen
  • 771
  • 7
  • 24
  • Why you just can't use pair thread-handler? Handler helps to display all info on ui-thread. It is the simplest way. More difficult way is to use rxjava library, for example. – white-imp Oct 03 '20 at 19:55
  • I'm not familiar with Handlers and read that ```runOnUIThread()``` is an easy way to update the UI. – John Glen Oct 03 '20 at 19:56
  • You'll have to be familiar with this, it's the one of the fundamental things. – white-imp Oct 03 '20 at 21:07
  • I looked at the developers page for Handlers and it seems like overkill for my small project. I really just want to know if code run from a Fragment is in the UI thread. – John Glen Oct 03 '20 at 21:21

1 Answers1

0

The fragment itself as an object is not a part of the UI. However, the root view of the fragment is a part of this UI. What I mean is that the view you are returning back from the onCreateView() method is representing your UI and if you need to update any element in this view such as TextViews or Buttons from any other thread, you definitely have to use runOnUIThread(new Runnable(){...}); method.

Remark

If you are using RxJava or Coroutines this operation will be much easier for you as it makes switching threads very easy.

Hamza Sharaf
  • 811
  • 9
  • 25