i got a problem in updating progress bar. I am updating progress bar in separate Thread and the variable on which the progressbar progress is depending(which is a class variable) updating in another thread. So, the progress dialog shows but always 0% not updating it progress. Help me please.
public void setProgressbar()
{
progressBar = new ProgressDialog(context);
progressBar.setCancelable(true);
progressBar.setMessage("File downloading ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
Thread thread = new Thread()
{
public void run()
{
while(progressBar.getProgress() < 100)
{
Log.v("progressbar", getProgress()+"");
progressBar.setProgress(getProgress());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
thread.start();
Update value code
Thread thread = new Thread()
{
public void run()
{
.
.
.
while((bytesRead = is.read(bytearray, 0, bytearray.length)) != -1)
{
bos.write(bytearray, 0, bytesRead);
totaldownload = totaldownload + bytesRead;
Log.v("downloadign ", totaldownload+"");
// progressBar.setProgress((int) ((totaldownload/sizeoffile) * 100));
}
bos.close();
.
.
.
};
thread.start()
And getPrgoress method
public int getProgress()
{
return (int) ((totaldownload/sizeoffile) * 100);
}
Try this.
declare this variable at Global.
Following function call where you need it.
It's a Bug in ProgressBar!
The
setProgress(...)
seems to not trigger the update on thedrawable
if the same value is passed again. But it's not triggered during thesetMax
, too. So the update is missing.To solve this, I'm just doing a
bar.setProgress(0)
before each update... this is only a workaround, but it works for me as expected:Second Option.
it may also work for someone.
Use AsyncTask, there is also an example in this document to answer your need.
This code from AsyncTask actually do what you want to accomplish.
Only thing you need to change setProgressPercent() to your method name of progress bar value change. You could delete onPostExecute method AFAIK if you don't need it. Try to use AsyncTask instead of java Thread since AsyncTask provide methods already for your need while you need to write them if you use Thread instead.
You are updating progress bar inisde a thread's run method. you cannot update ui from a thread. You need to update ui on the ui thread. Use
runOnUiThread
.runOnUiThread
is a method of activity class.Or Use Asynctask.
http://developer.android.com/reference/android/os/AsyncTask.html
In asynctask
doInBackground
you can callpublishProgress(Progress...)
to publish one or more units of progress. These values are published on the UI thread, in theonProgressUpdate(Progress...)
step.There are something wrong with your logic. Change your thread to following