Reputation: 115
I have a doubt regarding progress bar in android. I haven't implemented it yet but due to shortage of time i want to make sure when i implement i better be clear with what is going to happen and why..
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Loading...");
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// reset the bar to the default value of 0
dialog.setProgress(0);
// get the maximum value
EditText max = (EditText) findViewById(R.id.maximum);
// convert the text value to a integer
int maximum = Integer.parseInt(max.getText().toString());
// set the maximum value
dialog.setMax(maximum);
// display the progressbar
dialog.show();
// create a thread for updating the progress bar
Thread background = new Thread (new Runnable() {
public void run() {
try {
// enter the code to be run while displaying the progressbar.
//
// This example is just going to increment the progress bar:
// So keep running until the progress value reaches maximum value
while (dialog.getProgress()<= dialog.getMax()) {
// wait 500ms between each update
Thread.sleep(500);
// active the update handler
progressHandler.sendMessage(progressHandler.obtainMessage());
}
} catch (java.lang.InterruptedException e) {
// if something fails do something smart
}
}
});
// start the background thread
background.start();
}
// handler for the background updating
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(increment);
}
};
This is the above code i took from somewhere...As this code says i have to keep my actual code below try in order to keep progress bar running.. My doubt is my code is a very lengthy one consisting of nested for loops ( parsing an entire file with all those bits and bytes) .. if i keep my lengthy process at that part of the section, how can it update the progress bar until it finishes its task ? Am i missing some concept ? please explain me how can i keep my process running and also update progress bar?
Upvotes: 0
Views: 1062
Reputation: 5935
I think the concept that you are missing is that if you want to to multiple things (showing progress in a progress bar and doing some actual work) you need to use multiple threads. That is why you need to create a separate thread to do the actual work.
And even if your code is really length, try re-factoring it, splitting it up into new classes and methods.
Upvotes: 0
Reputation: 2176
You should use AsynTask and show your ProgreesBar in its onPreExecute()
method and dismiss the ProgressBar in its onPostExecute()
method. Do all your Loading Stuff in doInBackground()
method.Further, to update ProgressBar use onProgressUpdate()
This will help : http://developer.android.com/reference/android/os/AsyncTask.html
Upvotes: 1