Skip to content

Instantly share code, notes, and snippets.

@victor-geere
Last active September 19, 2016 09:30
Show Gist options
  • Save victor-geere/740d291cfbc954387a08 to your computer and use it in GitHub Desktop.
Save victor-geere/740d291cfbc954387a08 to your computer and use it in GitHub Desktop.
Android GET json in AsyncTask
public class HttpAsyncTask extends AsyncTask<String, Void, Integer> {
private Context mContext;
public HttpAsyncTask(Context context) {
mContext = context.getApplicationContext();
}
@Override
protected void onPreExecute() {
}
@Override
protected Integer doInBackground(String... params) {
try {
URL myURL = new URL(params[0]);
URLConnection conn = myURL.openConnection();
InputStream is = conn.getInputStream();
BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONObject response = new JSONObject(responseStrBuilder.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
@Override
protected void onPostExecute(Integer integer) {
}
}
private void getFiles() {
HttpAsyncTask myTask = new HttpAsyncTask(this);
myTask.execute("http://weather.com/json");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment