Android Open Source - SimpleWeather Remote Fetch






From Project

Back to project page SimpleWeather.

License

The source code is released under:

Apache License

If you think the Android project SimpleWeather listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.eventbooking.simpleweather;
/*from www .  ja v  a 2  s  .  c o m*/
import android.content.Context;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class RemoteFetch {
    private static final String OPEN_WEATHER_MAP_API = "http://api.openweathermap.org/data/2.5/weather?q=%s&units=imperial";

    public static JSONObject getJson(Context context, String city) {
        try {
            URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
            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()));

            StringBuilder json = new StringBuilder(1024);
            String line;

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

            reader.close();

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

            if (data.getInt("cod") != 200) {
                return null;
            }

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




Java Source Code List

com.eventbooking.simpleweather.ApplicationTest.java
com.eventbooking.simpleweather.CityPreference.java
com.eventbooking.simpleweather.RemoteFetch.java
com.eventbooking.simpleweather.WeatherActivity.java
com.eventbooking.simpleweather.WeatherFragment.java