Last active
January 5, 2023 08:14
-
-
Save underhilllabs/458b069f8153cd02a5cd to your computer and use it in GitHub Desktop.
example AsyncTask in android
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
private class FetchWeatherTask extends AsyncTask<Void, Void, Void> { | |
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName(); | |
// These two need to be declared outside the try/catch | |
// so that they can be closed in the finally block. | |
HttpURLConnection urlConnection = null; | |
BufferedReader reader = null; | |
// Will contain the raw JSON response as a string. | |
String forecastJsonStr = null; | |
@Override | |
protected Void doInBackground(Void... params) { | |
try { | |
// Construct the URL for the OpenWeatherMap query | |
// Possible parameters are avaiable at OWM's forecast API page, at | |
// http://openweathermap.org/API#forecast | |
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=80223,USA&mode=json&units=metric&cnt=7"); | |
// Create the request to OpenWeatherMap, and open the connection | |
urlConnection = (HttpURLConnection) url.openConnection(); | |
urlConnection.setRequestMethod("GET"); | |
urlConnection.connect(); | |
// Read the input stream into a String | |
InputStream inputStream = urlConnection.getInputStream(); | |
StringBuffer buffer = new StringBuffer(); | |
if (inputStream == null) { | |
// Nothing to do. | |
forecastJsonStr = null; | |
} | |
reader = new BufferedReader(new InputStreamReader(inputStream)); | |
String line; | |
while ((line = reader.readLine()) != null) { | |
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing) | |
// But it does make debugging a *lot* easier if you print out the completed | |
// buffer for debugging. | |
buffer.append(line + "\n"); | |
} | |
if (buffer.length() == 0) { | |
// Stream was empty. No point in parsing. | |
forecastJsonStr = null; | |
} | |
forecastJsonStr = buffer.toString(); | |
} catch (IOException e) { | |
Log.e("ForecastFragment", "Error ", e); | |
// If the code didn't successfully get the weather data, there's no point in attemping | |
// to parse it. | |
forecastJsonStr = null; | |
} finally { | |
if (urlConnection != null) { | |
urlConnection.disconnect(); | |
} | |
if (reader != null) { | |
try { | |
reader.close(); | |
} catch (final IOException e) { | |
Log.e("ForecastFragment", "Error closing stream", e); | |
} | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment