E
E
Egor Kazantsev2015-01-27 08:50:07
Java
Egor Kazantsev, 2015-01-27 08:50:07

Accessing ProgressBar from AsyncTask?

There is something like this code:

class DownloadEventData
{
   private Integer i1;
   private Integer i2;
  public DownloadEventData(Integer i1 , Integer  i2) 
  {
     this.i1 = i1;
     this.i2 = i2;
  }
  Тут геттеры и сеттеры
}
class DownloadTask extends AsyncTask<String,DownloadEventData,Integer>
{
       private ProgressBar pb;
       public void setPb(ProgressBar p)
       {
              this.pb = p;
       }
       @Override
  protected String doInBackground(String... params) {
           ...
             publishProgress(new DownloadEventData([сколько скачалось],[сколько всего качать]));
           ...
        }
       @Override
  protected void onProgressUpdate(DownloadEventData...values) {
                 this.pb.setMax(values[0].getI2);
                 this.pb.setProcess(values[0].getI1);
    super.onProgressUpdate(values);
  }
  //---------------------------------------------------------------
  protected void onPreExecute(Integer result) 
  {
    super.onPreExecute();
  }
  @Override
  protected void onPostExecute(Integer result) 
  {
    
  }
}

And I use code like this:
ProgressBar ppp = (ProgressBar) findViewById(R.id.progressbar);
DownloadTask dt = new DownloadTask();
dt.setPd(ppp);
dt.execute("http://yandex.ru");

This case falls on this.pb.setMax(values[0].getI2); c
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setMax(int)' on a null object reference

It doesn’t even crash, but goes to finally where e.printStackTrace()
As far as I understand, only doInBackground is in a separate thread, and everything else is in the UI - so there shouldn’t be such problems, what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
anyd3v, 2015-01-27
@saintbyte

I would be in your place
1. Check if it is installed correctly
2. Make a constructor for DownloadTask with a ProgressBar parameter, and not through a setter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question