Fetching data (responsebody) with a HttpClient in an AsyncTask and returning the data outside the As
- by Peter Warbo
Basically I'm wondering how I'm able to do what I've written in the topic. I've looked through many tutorials on AsyncTask but I can't get it to work. I have a little form (EditText) that will take what the user inputs there and make it to a url query for the application to lookup and then display the results.
What I think would seem to work is something like this: In my main activity i have a string called responseBody. Then the user clicks on the search button it will go to my search function and from there call the GrabUrl method with the url which will start the asyncdata and when that process is finished the onPostExecute method will use the function activity.this.setResponseBody(content).
This is what my code looks like simpliefied with the most important parts (I think).
public class activity extends Activity {
private String responseBody;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
public void initControls() {
fieldSearch = (EditText) findViewById(R.id.EditText01);
buttonSearch = (Button)findViewById(R.id.Button01);
buttonSearch.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ search();
}});
}
public void grabURL(String url) {
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Void, String> {
private final HttpClient client = new DefaultHttpClient();
private String content;
private boolean error = false;
private ProgressDialog dialog = new ProgressDialog(activity.this);
protected void onPreExecute() {
dialog.setMessage("Getting your data... Please wait...");
dialog.show();
}
protected String doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
content = client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
error = true;
cancel(true);
} catch (IOException e) {
error = true;
cancel(true);
}
return content;
}
protected void onPostExecute(String content) {
dialog.dismiss();
if (error) {
Toast toast = Toast.makeText(activity.this, getString(R.string.offline), Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 0, 75);
toast.show();
} else {
activity.this.setResponseBody(content);
}
}
}
public void search() {
String query = fieldSearch.getText().toString();
String url = "http://example.com/example.php?query=" + query; //this is just an example url, I have a "real" url in my application but for privacy reasons I've replaced it
grabURL(url); // the method that will start the asynctask
processData(responseBody); // process the responseBody and display stuff on the ui-thread with the data that I would like to get from the asyntask but doesn't obviously
}