Android Progressbar not updating
Asked Answered
C

5

0

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);
    }
Cenotaph answered 18/9, 2013 at 7:46 Comment(5)
I might be wrong but that doesn't look thread save...Loment
where do you increment you progress value?Lushy
@Lushy i edit the post now u can see where i am updating the dependetn valueCenotaph
@MarioLenci why getProgress()+1 ??Cenotaph
@Cenotaph sry i missed a part of your answear. i tought you were updating the setPregress() with the progressBar.getProgress() :\Tentmaker
S
8

It's a Bug in ProgressBar!

The setProgress(...) seems to not trigger the update on the drawable if the same value is passed again. But it's not triggered during the setMax, 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:

bar.setProgress(0); // call these two methods before setting progress.
bar.setMax(20);
bar.setProgress(20);

Second Option.

mSeekBar.post(new Runnable() {
        @Override
        public void run() {
            mSeekBar.setProgress(percentOfFullVolume);
        }
    });

it may also work for someone.

Skidmore answered 10/2, 2015 at 13:42 Comment(5)
Has this been fixed? @Nepster?Holmes
I've been struggling with a progress bar that won't update to the current progress after the app has gone to standby/doze. Do you think runOnUiThread() would cause any issues with updating the front end?Holmes
'runOnUiThread()' wouldn't cause any issue.Or you can alternatively use Handler(); which also work on main UISkidmore
What would the benefit of using a handler be? Also do you know of any workarounds to this using different widgets ?Holmes
Set progress bar to 0, set it max and set it new progress worked for me!Sideburns
L
3

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 call publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

Lushy answered 18/9, 2013 at 7:49 Comment(0)
E
1

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.

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }
  }

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.

Ep answered 18/9, 2013 at 7:49 Comment(4)
add a bit more information to make the answer better, was thinking of posting something simularLoment
Linked document already has great example to do task. I think reading/applying this give enough info to handle OPs problem.Ep
It is better to quote something from that page, look at this and this as it will explain my reasoningLoment
Hmm, you are right actually. I think, I was just lazy. Thanks for warning.Ep
A
1

There are something wrong with your logic. Change your thread to following

Thread thread = new Thread()
{
    public void run()
    {
        int prog = 0;
         while(prog < 100)
         {

             progressBar.setProgress(prog);
             try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
             prog ++;
         }
    }
};
thread.start();
Alar answered 18/9, 2013 at 8:4 Comment(2)
in my case the variable which is passing to setProgress() is updating in another thread not in current thread see the edit in my postCenotaph
@Cenotaph use asynctask and use publish proress. check the docs posted in my postLushy
I
0

Try this.

declare this variable at Global.

int delay = 100;
int period = 2000;

Following function call where you need it.

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();

    final Handler mhandler = new Handler();

    final Runnable mRunnable = new Runnable() {

        @Override
        public void run() {

            progressBar.setProgress(progress);
            progress++;

        }
    };
    final Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {

            mhandler.post(mRunnable);

        }
    }, delay, period);
}
Incrocci answered 18/9, 2013 at 8:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.