Igor
Igor

Reputation: 105

ProgressBar in Android shows only after completing some operation

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.

Upvotes: 0

Views: 55

Answers (1)

Zain
Zain

Reputation: 40830

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.

Upvotes: 1

Related Questions