0

Here's the deal, I need to run an operation, and show a progress bar while it runs. I figured I need to run the progress bar update on a different thread, because if I don't (I have tried) the bar doesn't get updated before the end of the operation. I have written the code bellow, however it isn't working, crashing the app instead. I believe the problem is related to the synchronization between threads, but I'm not sure (second time working with Java threads, please spare me, I'm still a newbie). This is running on Android.

Can you spot any illegal operation I'm not aware of? Thanks!

ProgressDialog progress; //Global, declared somewhere else


final Object flag = new Object();
Thread progressThread;
//More Code...

progress.show();
progress.setMax(auxMobile.size() + auxStatic.size() );
progress.setProgress(0);

progressThread = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            synchronized (flag) {
                while (progress.getProgress() < progress.getMax()) {
                    progress.incrementProgressBy(1);
                    flag.wait();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        }
    });
progressThread.start();



try {

    for(int i=0; i<auxStatic.size(); i++) {
        //More Code...
        flag.notify();
    }

    for(int i=0; i<auxMobile.size(); i++){
        //More Code...
        flag.notify();
    }



    } catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
AmiguelS
  • 805
  • 2
  • 10
  • 28

1 Answers1

0

You really should use AsyncTask in that case. Check this, this.

It's gonna make your dev life for that case a hell lot easier !

Community
  • 1
  • 1
Leonardo
  • 3,141
  • 3
  • 31
  • 60