Jakob Jakob - 2 months ago 11
Android Question

Fetch temperature from JSON

I am building an Android app where I want to read the current temperature in my city. I am using the http://openweathermap.org/current free API.

Now, when I when I try to fetch the temperature by doing the following:

@Override
public void onResponse(JSONObject response) {

try {

Log.d("MY LOGGER: ", "Task started");

//Fetch description
JSONArray measurements = response.getJSONArray("list");
String desc = measurements.getJSONObject(0).getJSONArray("weather").getJSONObject(0).getString("description");

//Fetch temp
JSONObject currentTemp = response.getJSONObject("main");
double temp = currentTemp.getDouble("temp");
.
.


The "desc" or description is fetched as expected, buy the fetching of the temperature says:


W/System.err: org.json.JSONException: No value for main
W/System.err: at org.json.JSONObject.get(JSONObject.java:389)
W/System.err: at org.json.JSONObject.getJSONObject(JSONObject.java:609)


Here is a snippet of the JSON I receive, note "lon":xxx,"lat":xxx is on purpose:

{"city":{"id":2624652,"name":"Arhus","coord":{"lon":xxx,"lat":xxx},"country":"DK","population":0,"sys":{"population":0}},"cod":"200","message":0.0028,"cnt":40,"list":[{"dt":1475269200,"main":{"temp":284.9,"temp_min":284.897,"temp_max":284.9,"pressure":1017.03,"sea_level":1020.8,"grnd_level":1017.03,"humidity":79,"temp_kf":0},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"clouds":{"all":48},"wind":{"speed":6.75,"deg":247.005},"rain":{"3h":0.04},"sys":{"pod":"n"},"dt_txt":"2016-09-30 21:00:00"},{"dt":1475280000,"main":{"temp":284.21,"temp_min":284.205,"temp_max":284.21,"pressure":1017.5,"sea_level":1021.27,"grnd_level":1017.5,"humidity":87,"temp_kf":0},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}] ...


What am I doing wrong in the fetching?

Answer

UPDATED

Try fetching it this way.

       JSONArray measurements = response.getJSONArray("list");
                 //description                
                String desc = measurements.getJSONObject(0).getJSONArray("weather").getJSONObject(0).getString("description");
                //temperature
                double temp = measurements.getJSONObject(0).getJSONObject("main").getDouble("temp");