0

Consider the code below:

package com.reallybelievebig.asynctaskextracredit;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class AsyncTaskTestActivity extends AppCompatActivity {

    private static final String TAG = AsyncTaskTestActivity.class.getSimpleName();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_task_test);

        new TestTask().execute("Execute");

        Log.d(TAG, "In UI Thread!");
    }

    private class TestTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... params) {
            for (int i = 0; i <= 100; i+=20) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    Log.e(TAG, "Exception Caught: ", e);
                }

                publishProgress(i);
            }

            return "Background Task Complete";
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            Toast.makeText(AsyncTaskTestActivity.this, "Progress: " + values[0], Toast.LENGTH_LONG).show();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.d(TAG, "In onPostExecute: " + s);
            Toast.makeText(AsyncTaskTestActivity.this, s, Toast.LENGTH_LONG).show();
        }
    }

}
  1. I am starting an asynchronous task from the main UI thread using TestTask.execute() method.

  2. The doInBackground() method is working fine. It sleeps for some time, invokes the publishProgress() method and displays the Toast in onProgressUpdate() method.

  3. I was expecting that the onPostExecute() method to be called only after the doInBackground() is completed. However as soon as I start the Application, I get the Log message in onPostExecute() method.

There is something wrong which I am not able to figure out. What is the issue in this code?

nitin_cherian
  • 6,405
  • 21
  • 76
  • 127

0 Answers0