skip to Main Content

I have a method in which I want a delay of a second, and while the delay is running there should be a loading animation (ProgressBar).

Right now, when the method is now running the loading animation is not appearing. If I do not call the Timeout it does appear, and when I do not make it invisible after, it shows up after the timeout.

How do I show the loading animation while the timeout is running? I have a similar problem trying to do with with Thread.sleep(1000).

public void firstMethod(){
    ProgressBar pgLoading = (ProgressBar) findViewById(R.id.pgLoading);
    
    pgLoading.setVisibility(VISIBLE);
    
    try {
        TimeUnit.SECONDS.sleep(1);
    }catch(InterruptionException ex){
        ex.printStackTrace();
    }

    pgLoading.setVisibility(INVISIBLE);
}

3

Answers


  1. By calling the sleep method you are making the UI thread sleep for 1 second during that time nothing will happen on UI Thread hence you do not see the ProgressBar. You should instead use a TimerTask to wait for this one second and then close the ProgressBar.
    Checkout this link on how to use TimerTask.

    Login or Signup to reply.
  2. Main thread can’t be blocked. That will cause the entire rendering to stop. That’s why you only see the result after that timeout.

    These kind of operations shoud be handled in other threads. If you are using Java you can use Runnables but you should consider moving to Kotlin to use coroutines.

    E.G:

        pgLoading.setVisibility(VISIBLE);
        new Thread() {
            public void run() {
                Thread.sleep(1000);
                runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                      pgLoading.setVisibility(INVISIBLE);
                   }
                });
               }
              }
            }.start();
    
    Login or Signup to reply.
  3. This is happening because the current thread is being paused.To avoid this put your delay/long process in a different thread.For example:

    public void firstMethod(){
                ProgressBar pgLoading = (ProgressBar) findViewById(R.id.pgLoading);
    
                pgLoading.setVisibility(View.VISIBLE);
    new Thread(()->{
    //    Do all your long process here
        try {
            TimeUnit.SECONDS.sleep(1);
        }catch( InterruptedException ex){
            ex.printStackTrace();
        }
        runOnUiThread(() -> pgLoading.setVisibility(View.INVISIBLE));
    
    }).start();
    
    
    
    
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search