Saeed Sharman
Saeed Sharman

Reputation: 785

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;
    }

Upvotes: 1

Views: 1149

Answers (4)

saurabh169
saurabh169

Reputation: 589

what URL you have assigned to your OPEN_WEATHER_MAP_API..?

url should be- http://api.openweathermap.org/data/2.5/weather?q=city&units=metric

please try this...

Upvotes: 0

Saeed Sharman
Saeed Sharman

Reputation: 785

I had to add the following permission along with internet permission.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Upvotes: 1

Justice
Justice

Reputation: 464

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));

Upvotes: 1

SripadRaj
SripadRaj

Reputation: 1735

I'm commenting here as I don't have privilege to comment in your question thread. Print stack trace of your catch block, you may be able to find solution to your problem.

Upvotes: 1

Related Questions