1

I have a time consuming task that is taking place in the doInBackground() method, but from within that method, I want to be able to update the progressDialog with percentage data. How can I do this?

    class GetDataTask extends AsyncTask<Void, Void, Void> {     

    @Override
    protected void onPreExecute()
    {
        mProgressDialog = ProgressDialog.show(getActivity(),Constants.APP_NAME,"Getting data", true);
    }

    @Override
    protected Void doInBackground(Void... params)
    {
        //go get data, update mProgressDialog
        return null;
    }

    @Override
    protected void onPostExecute(Void res)
    {           

    }
}
user1154644
  • 4,491
  • 16
  • 59
  • 102

2 Answers2

2

Override the onProgressUpdate() method like this:

@Override
protected void onProgressUpdate(Integer... progress) {
    super.onProgressUpdate(progress);
    mProgressDialog.setProgress(progress[0]);
}

and publish the progress with

publishProgress((int) (total * 100 / fileLength));

Try to refer to this link

Community
  • 1
  • 1
K_Anas
  • 31,226
  • 9
  • 68
  • 81
0

AsyncTask has method onProgressUpdate(Integer...) that you can call each iteration for example or each time a progress is done during doInBackground() by calling publishProgress().

Refer to the docs for more details


Note that the second parameter is the progress variable

class GetDataTask extends AsyncTask<Void, String, Void> {     

    @Override
    protected void onPreExecute()
    {
        mProgressDialog = ProgressDialog.show(getActivity(),Constants.APP_NAME,"Getting data", true);
    }

    @Override
    protected Void doInBackground(Void... params)
    {
        publishProgress(""+(int)count);
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        /**
         * Sets current progress on ProgressDialog
         */
        mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(Void res)
    {           

    }
}
silentw
  • 4,835
  • 4
  • 25
  • 45
  • but how does AsyncTask know how far along it is, what is the measuring stick so to speak? – user1154644 Jul 26 '12 at 01:40
  • measuring unit? you can do it whatever you like, like the `alreadydownloaded/sizeoffile`, simple `43/100 %`, whatever you want it to display and update :) – silentw Jul 26 '12 at 16:46