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();
}
}
}
I am starting an asynchronous task from the main UI thread using
TestTask.execute()
method.The
doInBackground()
method is working fine. It sleeps for some time, invokes thepublishProgress()
method and displays the Toast inonProgressUpdate()
method.I was expecting that the
onPostExecute()
method to be called only after thedoInBackground()
is completed. However as soon as I start the Application, I get the Log message inonPostExecute()
method.
There is something wrong which I am not able to figure out. What is the issue in this code?