Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android AsyncTask's onProgressUpdate not working

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();
}
like image 552
Pramod Ravikant Avatar asked Feb 03 '26 01:02

Pramod Ravikant


1 Answers

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;
    }
like image 53
Waza_Be Avatar answered Feb 05 '26 14:02

Waza_Be



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!