Home > Enterprise >  Progressbar in Android Studio is not showing while delay
Progressbar in Android Studio is not showing while delay

Time:01-13

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

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

So, how do i show the loading animation while the timeout is running? Same problem 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);
}

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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




    }

CodePudding user response:

You can use delay

import android.os.Handler;

 
public void firstMethod()
{


//Initialize and make progress **strong text**bar visible here

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
    // Do something after 1s = 1000ms
      //Make your progress bar invisible 

 }
 }, 1000);
 }        
  •  Tags:  
  • Related