Android ProgressBar: loading with Timer

acrichm picture acrichm · Dec 6, 2011 · Viewed 12.6k times · Source

Update: This post was from when I was learning android with android 2.2, be sure to check if this is compatible with the api level you are working with.

Done alot of looking around for how to load progress bar with a timer, I've tried to use methods posted but always would get a pointer exception and or the testing app would crash at start up.

my question is, lol has anyone ran across any tutorials or examples on how to do this? I'm thinking all i need is a while loop but haven't seen that done on a timer yet. I'm a complete noob but am slowly but surely learning

My Timer

final Timer t = new Timer();
    t.schedule(new TimerTask() {
        public void run() {
            d.dismiss();  //MY DIALOG WINDOW
            t.cancel();
        }
    }, 7000);   

this is one i have tried to get to work but think i have done more damage then good with it

isRunning = false;
    // handler for the background updating
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            total = total - 1;
            String perc = String.valueOf(total).toString();
            a.setText(perc + " SECONDS  until close");
            bar.incrementProgressBy(25);
        }
    };

    super.onStart();
    // reset the bar to the default value of 0
    bar.setProgress(0);
    // create a thread for updating the progress bar
    Thread background = new Thread(new Runnable() {
        public void run() {
            try {
                for (int i = 4; i < 20 && isRunning; i++) {
                    // wait 1000ms between each update
                    Thread.sleep(1000);
                    handler.sendMessage(handler.obtainMessage());
                }
            } catch (Throwable t) {
            }
        }
    });
    isRunning = true;
    // start the background thread
    background.start();

hoping someone might be able to shed some light on this for me,, as always sorry for the short generic question, just looking to find out how to load progress bar with timer

tahnks again for any and all help

Answer

NKijak picture NKijak · Dec 7, 2011

Use a android.os.CountDownTimer

 countDownTimer = new CountDownTimer(length_in_milliseconds,period_in_milliseconds) {
        private boolean warned = false;
        @Override
        public void onTick(long millisUntilFinished_) {
           progressBar.progress = (length_in_milliseconds-millisUntilFinished_)/lenght_in_milliseconds*100.0;
        }

        @Override
        public void onFinish() {
            // do whatever when the bar is full
        }
    }.start();