Skip to content Skip to sidebar Skip to footer

Asynctask Onpostexecute Call From Outside The Asynctask

I want to use the same AsyncTask in different places on my App and I want a different onPostExecute for each one. It's possible to call them from onCreate method instead of from As

Solution 1:

Just create an AsyncTask with no onPostExecute method overridden

publicclassYourTaskextendsAsyncTask<Whatever, Whatever, Whatever> {

    @Overrideprotected Whatever doInBackground(Whatever... whatever) {
        // whateverreturn whatever;
    }

}

And then when you want different implementations of onPostExecute, create anonymous task or descendant class and use it

task = newYourTask() {

    @OverrideprotectedvoidonPostExcecute(Whatever result) {
        //whatever
    }

};
task.execute();

Or better

publicclassYourTaskAnotherextendsYourTask {

    // just override onPostExecute here@OverrideprotectedvoidonPostExcecute(Whatever result) {
        //whatever
    }
}

task = newYourTaskAnother();
task.execute();

Solution 2:

What you can do is to add a switch case in the onPostExecute() method depending on all possible scenarios. Then inside the AyncTask add a constructor using which you could pass the type.

DownloadTaskextendsAsyncTask ...
{
    int postExecuteType; 
    publicDownloadTask(int type) {
        this.postExecuteType = type; 
    }
...

    protectedvoidonPostExecuted()
    {
        switch(type) {
            case1:
            break;
        }
    }

}

Now just call newDownloadTask(1).execute();

Post a Comment for "Asynctask Onpostexecute Call From Outside The Asynctask"