-1

Im trying to do a GET request to a server and return the response. Here is my code.

@Override
protected String doInBackground(String... params) {
    String url = getBaseUrl() + params[0] + "?" + params[1] + "=" + params[2];
    String response = "";
    try {
        HttpClient client = new DefaultHttpClient();
        String getURL = url;
        HttpGet get = new HttpGet(getURL);
        HttpResponse responseGet = client.execute(get);
        HttpEntity resEntityGet = responseGet.getEntity();
        if (resEntityGet != null) {
            // do something with the response
            response = EntityUtils.toString(resEntityGet);
            return response;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

When debugging response has the right value but when I call the method the response becomes something else. I call it like this:

 HTTPConnector connector = new HTTPConnector("http://www.thetvdb.com/api/");
    try {
        AsyncTask<String, Void, String> result = connector.execute("GetSeries.php", "seriesname", "Arrow");
        String result2 = result.toString();
        System.out.println(result2);
    } catch (Exception e) {
        e.printStackTrace();
    }

The result here is something else than the response in the doInBackground method. How is this possible and how can I fix this?

bpncool
  • 131
  • 1
  • 13
Jelle van Es
  • 613
  • 6
  • 20
  • See [this answer](http://stackoverflow.com/questions/18898039/using-asynctask/18898105#18898105) on using `AsyncTask`. You can't get the result until the task has finished – codeMagic Feb 26 '15 at 15:19

2 Answers2

1

As see doc AsyncTask.execute task returns itself (this) so that the caller can keep a reference to it which we will use to check the status of AsyncTask like is task is running,pending or finished instead of return result of doInBackground.

onPostExecute method is called when doInBackground method execution done to deliver result to UI Thread:

@Override
protected void onPostExecute(String result) {
    // update UI here
}
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
0

You use AsyncTask in a wrong way. You should get the response String in its onPostExecute() method, code like this:

    @Override
    protected void onPostExecute(String result) {
        // The result is the response String you want.
    }
Lei Guo
  • 2,550
  • 1
  • 17
  • 22