3

I have an AsyncTask in a class. I want it to display the progress while it is getting executed. But it is not printing the Logs.

private void registerBackground() {
    new AsyncTask<Void, Integer, String>() {

        @Override
        protected String doInBackground(Void... params) {
            Log.v("TAGGG", "IN doInBackground");
            msg = "Error: ";

            return msg;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            Log.v("TAGGG", "Progress: " + progress[0] + "%");
        }

        @Override
        protected void onPostExecute(String msg)
        {
            Log.v("TAGGG", msg);
        }
    }.execute();
}
Pramod Ravikant
  • 1,039
  • 2
  • 11
  • 28

1 Answers1

9

You have to use the publishProgress() method: http://developer.android.com/reference/android/os/AsyncTask.html#publishProgress(Progress...)

This method can be invoked from doInBackground(Params...) to publish updates on the UI thread while the background computation is still running. Each call to this method will trigger the execution of onProgressUpdate(Progress...) on the UI thread. onProgressUpdate(Progress...) will note be called if the task has been canceled.

    @Override
    protected String doInBackground(Void... params) {
        Log.v("TAGGG", "IN doInBackground");
        msg = "Error: ";
        int i = 0;
        while (i <= 50) {
            try {
                Thread.sleep(50);
                publishProgress(i);
                i++;
            }
            catch (Exception e) {
                Log.i(TAGGG, e.getMessage());
            }
        }
        return msg;
    }
Waza_Be
  • 39,407
  • 49
  • 186
  • 260
  • 1
    Why that `while` code? And Why `sleep` ? Won't it make it slow? – Pramod Ravikant Jul 27 '13 at 06:09
  • 2
    @micro.pravi the objective in an Asynctask is to simulate a long thread (downloading data, parsing a huge file) and displaying progress to the user.. The sleep is not meant to be on a production code! – Waza_Be Jul 27 '13 at 06:30