Skip to content

Instantly share code, notes, and snippets.

@danieloskarsson
Last active May 11, 2020 09:06
Show Gist options
  • Save danieloskarsson/822b6be9dc4b3471910f6dfe1443b892 to your computer and use it in GitHub Desktop.
Save danieloskarsson/822b6be9dc4b3471910f6dfe1443b892 to your computer and use it in GitHub Desktop.
@SuppressLint("StaticFieldLeak")
private class JsonTask extends AsyncTask<String, String, String> {
private HttpURLConnection connection = null;
private BufferedReader reader = null;
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null && !isCancelled()) {
builder.append(line).append("\n");
}
return builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String json) {
Log.d("TAG", json);
}
}
@danieloskarsson
Copy link
Author

danieloskarsson commented Apr 27, 2020

Copy the class content and put it inside MainActivity but not inside a method. Invoke like this: new JsonTask().execute("HTTPS_URL_TO_JSON_DATA");, e.g. in a button click handler in onCreate(). onPostExecute(String json) will be automatically invoked with the json result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment