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

The only way to do this is using a CallBack. You can do something like this:

new CallServiceTask(this).execute(request, url);

Then in your CallServiceTask add a local class variable and call a method from that class in your onPostExecute:

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

    CallServiceTask(RestClient caller) {
        this.caller = caller;
    }


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

    protected onPostExecute(Object result) {
        caller.onBackgroundTaskCompleted(result);
    }
}

Then simply use the Object as you like in the onBackgroundTaskCompleted() method in your RestClient class.

A more elegant and extendible solution would be to use interfaces. For an example implementation see this library. I’ve just started it but it has an example of what you want.

Leave a Comment