Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding pre/post execute in AsyncTask and calling super.onPre/PostExecute

Is it mandatory to call super.onPreExecute when overriding onPreExecute in an AsyncTask? What does AsyncTask.onPreExecute and other methods actually do? Same question for onPostExecute and onCancelled

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

@Override
protected void onCancelled(Boolean result) {

    super.onCancelled(result);   //<-DO I HAVE TO?

            //My onCancelled code below


}

@Override
protected void onPostExecute(Boolean result) {

    super.onPostExecute(result);  //<-DO I HAVE TO?

            //My onPostExecute code below
}

@Override
protected void onPreExecute() {

    super.onPreExecute();  //<-DO I HAVE TO?

            //My onPreExecute code below

}

@Override
protected Boolean doInBackground(Void... params) {

    return null;
}
like image 618
Mar Bar Avatar asked Feb 11 '14 13:02

Mar Bar


2 Answers

No, you don't need to call super. Here's the source.

As you can see, the default implementation does nothing.

/**
* Runs on the UI thread before {@link #doInBackground}.
*
* @see #onPostExecute
* @see #doInBackground
*/
protected void onPreExecute() {
}

/**
* <p>Runs on the UI thread after {@link #doInBackground}. The
* specified result is the value returned by {@link #doInBackground}.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* @param result The result of the operation computed by {@link #doInBackground}.
*
* @see #onPreExecute
* @see #doInBackground
* @see #onCancelled(Object)
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void onPostExecute(Result result) {
}
like image 164
Tyler MacDonell Avatar answered Sep 28 '22 15:09

Tyler MacDonell


No we don't compulsorily need to Override the methods onPreExecute & onPostExecute.

onPreExecute called before the doInbackground Process starts We can add code in this method which we have to do before any thing Start working doInbackground.

doInbackground works in background so in this method do whatever we want to do in background like calling web service and all. but CAUTION for this method is not to set the UI widgets in This method . If set it will give Exception.

onPostExecute called after the completion on doInbackground & in this method we are able to set the UI widgets and other code to set after the Webservice call completed.

OnCancelled A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true.

check this link. Hope this help you.

like image 30
i.n.e.f Avatar answered Sep 28 '22 15:09

i.n.e.f