how to hide a progressBar after a certain time

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 at the time of setting Visibility the following error appears

FATAL EXCEPTION: Thread-1087 Process: br.alphatec.ms_caliente_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, it was very fast, and if I increase the value (100) that is in the while it stops working

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

               cont += 1;           
            }

            progressBar.setVisibility(View.GONE);
        }
    }).start(); 
    
asked by anonymous 11.06.2017 / 22:44

1 answer

4

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

It would certainly be the first case because it is not busy.

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

To resolve the problem you need to continue processing on Main Thread after waiting on Thread separated.

The first example would look like this:

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 slightly more advanced things, I recommend that you take a look at the concept of AsyncTask .

Using AsyncTask your example would look like:

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);
    }
}

No AsyncTask method doInBackground is called on ThreadPoolExecutor and method onPostExecute on Main Thread .

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

    
11.06.2017 / 23:52