How to correctly start activity from PostExecute in Android?

You should pass in the application context rather than a context from the local activity. I.e. use context.getApplicationContext() and save that in a local variable in your AsyncTask subsclass.

The code might looks something like this:

public class MyAsyncTask extends AsyncTask {

    Context context;
    private MyAsyncTask(Context context) {
        this.context = context.getApplicationContext();
    }

    @Override
    protected Object doInBackground(Object... params) {
        ...
    }

    @Override
    protected void onPostExecute(List<VideoDataDescription> result) {
        super.onPostExecute(result);
        MainActivity.progressDialog.dismiss();

        context.startActivity(new Intent(context, ResultsQueryActivity.class));
    }
}

you’d call it like this:

   new MyAsyncTask(context).execute();

Leave a Comment