Search code examples
androidandroid-progressbartimertask

How can I show a few progress bars one by one?


I have to do something like this:

  • Iterate between a few records of an arraylist.
  • Show progressdialog for one record
  • Move to next record
  • and so on.

I am facing issues in showing progress dialog inside a for loop.

I have tried many variations of TimerTask and run. Here is my latest code of the sample demo application.

//In function of showing progress
for (int i = 0; i < myInfo.size() ; i++){
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new ProgressTask(timer), 1000, 1000);
}

//Here is the ProgressTask
public class ProgressTask extends TimerTask {
    Timer timer;
    public ProgressTask (Timer timer){
        this.timer = timer;
    }

    @Override
    public void run() {
        progressStatus = progressStatus + 10;
        progressBar.setProgress(progressStatus);
        if (progressStatus == 100) {
            timer.cancel();
        }
    }
}

Result is: I just see the progress dialog for first record. Though it executes for loop for all the records, I have made some mistake in scheduling task or my run thread or timer. Can someone help me with the mistake in my code?

Edit:

Here is the whole Activity's code if that helps.


Solution

  • Your progresstask executed simultaneously so you get only one progress. So adjust your delay to execute one by one.

    Try this

     for (int i = 0; i < 10 ; i++){
            Timer timer = new Timer();
            timer.scheduleAtFixedRate(new ProgressTask(timer),  i * 1000, 1000);
        }
    
     public class ProgressTask extends TimerTask {
        Timer timer;
        public ProgressTask (Timer timer){
            this.timer = timer;
        }
    
        @Override
        public void run() {
    
            progressStatus = progressStatus + 10;
            progressBar.setProgress(progressStatus);
            timer.cancel(); //Cancel timer all time bcoz you create new timer everytime.
    
        }
    
    }