0

I tried to use ProgressBar in my Activity when I execute a short-time operation. And I realized that when I set ProgressBar visibility to true, It becomes visible only after the operation was executed.

progressBar.setVisibility(View.VISIBLE);
calculate();
  

Then I found the solution that I have to set ProgressBar visibility in another Thread. So my question is: why do I have to set it in another Thread?

For example, if I leave my ProgressBar with true visibility on creation (in onCreate()), it will progress and I can interact with UI in that moment. I concluded that they execute in one thread and It's okay. But It seems to me I'm wrong.

Zain
  • 37,492
  • 7
  • 60
  • 84
Igor
  • 105
  • 8

1 Answers1

1

The Android UI toolkit is not thread-safe. This means that you must not manipulate your UI from a worker/background thread. you must do all manipulation to your user interface from the UI (Main) thread.

Android UI toolkit include elements in android.widget & android.view packages

Rule of Thumb:

  1. Do not block the UI thread (don't run operations that have unspecified time in UI thread)
  2. Do not access the Android UI toolkit from outside the UI thread

This is explained in more details in here

Running background threads using AsyncTask or Loaders always allow you to update your UI upon the background thread results in their onPostExecute() and onLoadFinished() respectively.

So, as of your question, you have to update your ProgressBar from the UI thread not from other threads.

Zain
  • 37,492
  • 7
  • 60
  • 84
  • But in my code I’m updating Progress Bar from UI thread. The problem is that it’s updating after the operation, even if in code I firstly updating progress bar and then doing some operation – Igor Feb 23 '19 at 14:32
  • maybe this operation takes some time which makes main UI unblocked until it's finished; so it might need to be in background thread. Does the PorgressBar value depends on the result on a partial result of this operation? – Zain Feb 23 '19 at 16:28
  • Oh, maybe. No, it doesn’t depend – Igor Feb 24 '19 at 06:34