Saeed Sharman Saeed Sharman - 6 months ago 41
JSON Question

Why dont open weather map api return data in android app?

I am trying to fetch JSON data from open weather map api with following code but it always gets fail. I dont know what exception happens and I always get null response as defined in the catch.

try {
//URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
URL url = new URL(String.format(OPEN_WEATHER_MAP_API));
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();

connection.addRequestProperty("x-api-key",
context.getString(R.string.open_weather_maps_app_id));

BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));

StringBuffer json = new StringBuffer(1024);
String tmp="";
while((tmp=reader.readLine())!=null)
json.append(tmp).append("\n");
reader.close();

JSONObject data = new JSONObject(json.toString());

// This value will be 404 if the request was not
// successful
if(data.getInt("cod") != 200){
return null;
}

return data;
}catch(Exception e){
return null;
}

Answer

Without, knowing how you are creating your URL, it looks like you are missing the city in your String.format

URL url = new URL(String.format(OPEN_WEATHER_MAP_API));

Shouldn't it be

URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));