Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Time delay in a loop with updating UI

What I'm trying to create is a simple progress bar, that would load for ~10 sec. So what I want is a for loop like this:

for(int i = 1; i <= 100; i++) {
                    progressDialog.setProgress(i);
                    //100ms delay
                }

Thanks

like image 781
Gregor Menih Avatar asked Feb 04 '26 08:02

Gregor Menih


2 Answers

You can use Async Task for the purpose

in preExecute() method initialize loop index to 0;

in background process sleep thread for 10 seconds, and then call sendUpdate method to send progress

in postExecute update progress bar to progress get in parameter.

like image 66
jeet Avatar answered Feb 05 '26 22:02

jeet


The following code may be helpful for you.

public void startProgress(View view) {
    // Do something long
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i <= 10; i++) {
                final int value = i;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.setProgress(value);
                    }
                });
            }
        }
    };
    new Thread(runnable).start();
}
like image 42
himanshu Avatar answered Feb 05 '26 21:02

himanshu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!