Retrieve and show data from APIs : Android

Being able to communicate with a server, using a friendly API and displaying the data is an essential skill for any Android Developer.

ASyncTask

Since UI operations take place on the main thread, any piece of code that can block the UI is not permitted on main thread. We need to perform API calls using another thread.

Lets fetch weather data.

public class FetchData extendsAsyncTask <String,Void,String[]>

We’ll be inputing a string and returning an array of strings.

We perform tasks inside the doInBackground() method.

Sending a GET request and fetching JSON response.

String url="http://api.openweathermap.org/data/2.5/forecast/daily?q=110003&mode=json&units=metric&cnt=7&APPID=2de143494c0b295cca9337e1e96b00e0"
URL url = new URL(url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));

String line;
while ((line = reader.readLine()) != null) { 
buffer.append(line + "\n");
}

if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();

try{
return forecastJsonStr;
}catch (JSONException e){
Log.e(LOG_TAG, e.getMessage(), e);
}

This is how our JSON string looks now:

{....
“cnt”: 7,
“list”: [
{
“dt”: 1452232800,
“temp”: {
“day”: 16,
“min”: 11.16,
“max”: 16,
“night”: 11.16,
“eve”: 16,
“morn”: 16
},
“pressure”: 1005.08,
“humidity”: 60,
“weather”: [
{
“id”: 800,
“main”: “Clear”,
“description”: “sky is clear”,
“icon”: “01d”
}
],
“speed”: 4.11,
“deg”: 319,
“clouds”: 0
},

We are interested in stuff inside list.

Parsing JSON string

JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray('list');
for(int i=0;i<weatherAray.length();i++){
JSONObject dayForecast = weatherArray.getJSONObject(i);
description = dayForecast.getJSONArray('weather').getJSONObject(0).getString('description');
...
}

Return the result

in the doInBackground() function

return resultStrs;

After getting result ?

Now we need to update the UI with the fetched data. This needs to be done on the UI thread.

Using onPostExecute() Function

protected void onPostExecute(String[] result) {
if (result != null) {
mForecastAdapter.clear();
for(String dayForecastStr : result) {
mForecastAdapter.add(dayForecastStr);
}
}
}

Here I am updating my adapter array with fetched string result array.

Done!