Last active
May 11, 2020 09:06
-
-
Save danieloskarsson/822b6be9dc4b3471910f6dfe1443b892 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 inonCreate()
.onPostExecute(String json)
will be automatically invoked with the json result.