How to get results of Async task

private class MyTask extends AsyncTask<X, Y, Z>

    protected void onPreExecute(){
// show a progress dialog
 protected Z doInBackground(X...x){
// consume X and create return result Z
// call updates on a dialog
 protected void onProgressUpdate(Y y){
// work with results Y
// dismiss a dialog

 X – The type of the input variables value you want to set to the background process. This can be an array of objects. 
Y – The type of the objects you are going to enter in the onProgressUpdate method. 
Z – The type of the result from the operations you have done in the background process.

In the main thread:

MyTask myTask = new MyTask();

if you call 
z= myTask.execute(x).get(); 
it's going to block the main thread and progress dialog won't show.

possible return values:

RUNNING – Indicates that the task is running.

PENDING – Indicates that the task has not been executed yet.

FINISHED – Indicates that onPostExecute(Z) has finished.

How do I get return values in a main thread? I’d like to have a callback in the main thread in the class where I called the task, so I can process return value (populate the screen with updated values for example)

This person describes how to get return values in the main thread by implementing an interface:

create interface class.

public interface AsyncResponse {
    void processFinish(String output);

in your Async class, you need to declare it (interface : AsyncResponse):

public class AasyncTask extends AsyncTask{
public AsyncResponse delegate=null;

   protected void onPostExecute(String result) {

final step: in your main Activity you need to implements interface you created earlierAsyncResponse.

public class MainActivity implements AsyncResponse{
   AasyncTask asyncTask =new AasyncTask();
    public void onCreate(Bundle savedInstanceState) {
     asyncTask.delegate = this;

   void processFinish(String output){
     //this you will received result fired from async class of onPostExecute(result) method.

I should try this approach tonight. 
Update: of course this works. However. If main class and the Async class are separated by couple more in call hierarchy (as in my case) I have to send the 
IAsyncResponse outputDelegate
as parameter in further up the chain to Async class has it.

One thought on “How to get results of Async task

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s