Question

I have the following code:

try {
    res = new Utils(ubc_context).new DownloadCalendarTask().execute().get();
} catch (InterruptedException e) {
    Log.v("downloadcalendar", "interruptedexecution : " + e.getLocalizedMessage());
    res = false;
} catch (ExecutionException e) {
    Log.v("downloadcalendar", "executionexception : " + e.getLocalizedMessage());
    res = false;
}

Log.v("displaymenu", "A");

public class Utils {

private Context context;

public Utils(Context context) {
    this.context = context;
}

public class DownloadCalendarTask extends AsyncTask<Void, Void, Boolean> {

    private ProgressDialog dialog;

    public DownloadCalendarTask() {

    dialog = new ProgressDialog(context);

    }

    protected void onPreExecute() {
        Log.v("preexecute", "A");
        dialog.setMessage("Loading calendar, please wait...");
        Log.v("preexecute", "B");
        dialog.show();
        Log.v("preexecute", "C");

    }

    protected Boolean doInBackground(Void... arg0) {
        // do some work here...
        return (Boolean) false;
    }

    protected void onPostExecute() {
        Log.d("utils", "entered onpostexecute");
        dialog.dismiss();
    }

}
}

The first part of code is attached to an onClick listener for a button. When I click the button the button flashes (as it does to show it has been clicked), and then after about 8 seconds the Loading dialog appears but never finishes.

According to logcat, as soon as I click the button onPreExecute is executed as is Dialog.show(), so my first problem is why is there this 8 second delay? During these 8 seconds, logcat shows that doInBackground is being executed. However, according to logcat (this is the second problem) onPostExecute is never called (and so Dialog.dismiss()) is never run.

Logcat shows that everything following DownloadCalendarTask().execute().get() is being executed, so it's as if onPostExecute has just been skipped.

Many thanks for your help!

Was it helpful?

Solution

You are calling AsyncTask.get() which causes the UI thread to be blocked while the AsyncTask is executing.

new DownloadCalendarTask().execute().get();

If you remove the call to get() it will perform asynchronously and give the expected result.

new DownloadCalendarTask().execute();

Edit: You will also need to update the parameters to your onPostExecute method, they need to include the result. e.g.

protected void onPostExecute(Boolean result) {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top