Alex Rivera | Logout

How do I retrieve the data from AsyncTasks doInBackground()?

Asked 2012-02-14T08:51:21.627
16

I'll keep this one as simple as I can.

I have a method in my control layer that uses a class CallServiceTask that extends AsyncTask. When calling new CallServiceTask().execute(parameters)
How do I retrieve the data returned from doInBackground? All the tutorials I've found use the class that extends AsyncTask directly from their Activity.
My problem is a little bit more complex than that.
All I want is to take the Object[] returned by doInBackground and set it to the private data members of my RestClient class.

CallServiceTask looks like this :

    private class CallServiceTask extends AsyncTask<Object, Void, Object[]>
{

    protected Object[] doInBackground(Object... params) 
    {
        HttpUriRequest req = (HttpUriRequest) params[0];
        String url = (String) params[1];

        return executeRequest(req, url);
    }
}

And my RestClient class looks like this:

public class RestClient
{

private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;

private JSONObject jsonData;

private Object[] rtnData;

private String url;

private boolean connError;

public int getResponseCode() {
    return responseCode;
}

/**
 * 
 * @return  the result of whether the login was successful by looking at the response parameter of the JSON object. 
 */
public Boolean DidLoginSucceed()
{
    // Will Crash on socket error
        return ((JSONObject) rtnData[0]).optBoolean("response");
}

public String GetToken()
{
    return jsonData.optString("token");
}

public RestClient(String url)
{
    this.url = url;
    params = new ArrayList<NameValuePair>();
    headers = new ArrayList<NameValuePair>();
    rtnData = new Object[]{ new JSONObject() , Boolean.TRUE  };
}

public void AddParam(String name, String value)
{
   
Edit
Report

1 Answer

9

You can use get() to retrieve your value/object back from AsyncTask.

new CallServiceTask().execute(parameters).get();

This will return you computed result that you are returning. But this will block your UI till your background process is completed.

Another option is to create an Interface or BroadcastReceiver that you return you the value as soon as your doInBackground() is completed. I had created a demo for the same using Interface and BroadcastReceiver you can check if from my github

Also, by using second approach your UI will not be blocked!

answered 2012-02-14T08:55:09.703

Your Answer