Skip to content

Instantly share code, notes, and snippets.

@DenWav
Created November 15, 2015 08:01
Show Gist options
  • Save DenWav/66c2db71faf70bc6a042 to your computer and use it in GitHub Desktop.
Save DenWav/66c2db71faf70bc6a042 to your computer and use it in GitHub Desktop.
Weather
public static String getWeather(String loc) throws IOException {
String city;
String state;
String temp;
String humidity;
String wind;
String conditions;
try {
String json = getTextFromUrl(new URL("/* super secret API key stuff */" + encode(loc) + ".json"));
JsonParser parser = new JsonParser();
JsonObject weather = (JsonObject) parser.parse(json);
JsonObject currentObs = weather.get("current_observation").getAsJsonObject();
JsonObject displayLoc = currentObs.get("display_location").getAsJsonObject();
city = displayLoc.get("city").getAsString();
state = displayLoc.get("state_name").getAsString();
temp = currentObs.get("temperature_string").getAsString();
humidity = currentObs.get("relative_humidity").getAsString();
wind = currentObs.get("wind_string").getAsString();
conditions = currentObs.get("weather").getAsString();
} catch (Exception e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
Log.e(errors.toString());
return loc + " not found.";
}
return "[Current Weather for " + city + ", " + state + "] [Conditions: " + conditions + "] [Temperature: " + temp +
"] [Humidity: " + humidity + "] [Wind: " + wind + "]";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment