how to hide a progressBar after given time

Asked

Viewed 379 times

0

I’m using the following code

   new Thread(new Runnable() {
        public void run() {
            while (cont < 100) {
                cont += 1;

                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            progressBar.setVisibility(View.GONE);
        }
    }).start(); 

The problem is that when setting Visibility the following error appears

FATAL EXCEPTION: Thread-1087 Process: br.alphatec.ms_cliente_alpha1, PID: 23000 android.view.Viewrootimpl$Calledfromwrongthreadexception: Only the original thread that created a view Hierarchy can touch its views.

And when the code was running like this, but very fast, and if I increase the value(100) that’s in while it stops working

   new Thread(new Runnable() {
        public void run() {
            while (cont < 100) {

               cont += 1;           
            }

            progressBar.setVisibility(View.GONE);
        }
    }).start(); 

1 answer

4


I found it strange that the second solution works, because it is still violating the single threading restriction of the framework.

The most certain would be the first case because it is not doing a busy wait.

Back to the problem, you can not modify Views being in a Thread separate from Main Thread.

To solve the problem you need to continue processing on Main Thread after waiting in the Thread separate.

The first example would be:

new Thread(new Runnable() {
    public void run() {
        while (cont < 100) {
            cont += 1;

            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        progressBar.post(new Runnable() {
            @Override
            public void run() {
                progressBar.setVisibility(View.GONE);
            }
        });
    }
}).start();

For things a little more advanced, I recommend you take a look at the concept of AsyncTask.

Using AsyncTask your example would be:

new AsyncTask<Void, Void, Void> {
    @Override protected Long doInBackground(Void... args) {
        while (cont < 100) {
            cont += 1;

            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override protected void onPostExecute(Void result) {
        progressBar.setVisibility(View.GONE);
    }
}

In the AsyncTask the method doInBackground is called in a ThreadPoolExecutor and the method onPostExecute in Main Thread.

There are other features on AsyncTask, but it is not the scope of the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.