Skip to content

Instantly share code, notes, and snippets.

@planetguru
Created March 26, 2013 10:05
Show Gist options
  • Save planetguru/5244298 to your computer and use it in GitHub Desktop.
Save planetguru/5244298 to your computer and use it in GitHub Desktop.
Android/Java code for managing download/service access tasks asynchronously via a generic query task and generic fetchdata method..
private class QueryTask extends AsyncTask<String, Void, String> {
String role = new String();
@Override
protected String doInBackground(String... querySections) {
/* querySections: requestURL, requestQuery, role (index/data) */
String data = "", requestQuery = new String();
role = querySections[2];
try {
requestQuery = URLEncoder.encode(querySections[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
data = fetchData(querySections[0] + requestQuery);
} catch (IOException e) {
e.printStackTrace();
}
return (data);
}
/* check role and act accordingly */
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (role.equals(new String("index"))) {
// do whatever
} else if (role.equals(new String("data"))) {
// do whatever
}
}
}
private String fetchData(String reqString) throws IOException {
int connectionTimeout = 4000;
int responseTimeout = 5000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout);
HttpConnectionParams.setSoTimeout(httpParameters, responseTimeout);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
HttpGet httpget = new HttpGet(reqString);
try {
HttpResponse response = client.execute(httpget);
HttpEntity httpEntity = response.getEntity();
inputStream = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
String retrievedLine = null;
while ((retrievedLine = reader.readLine()) != null) {
stringBuilder.append(retrievedLine + "\n");
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return (stringBuilder.toString());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment