From c1a0fdd0f7f993d641888937913b7a58978b09eb Mon Sep 17 00:00:00 2001 From: m-rm Date: Wed, 18 Nov 2015 13:47:38 +0100 Subject: [PATCH 01/23] Fix NumberFormatException when showing current weather for Ischgl, Austria (Wind direction and speed is an empty String) --- .../yahooweather/YahooWeatherProvider.java | 60 ++++++++----------- .../weather/lib/util/WeatherUtility.java | 24 ++++++++ 2 files changed, 49 insertions(+), 35 deletions(-) diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java index 9bbe98a..195bca4 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java @@ -44,8 +44,6 @@ import java.util.Date; import java.util.List; import java.util.Locale; -import java.util.UnknownFormatConversionException; - public class YahooWeatherProvider implements IWeatherProvider { @@ -76,12 +74,11 @@ public List getCityResultList(String data) throws WeatherLibException { int event = parser.getEventType(); City cty = null; - String tagName = null; String currentTag = null; // We start parsing the XML while (event != XmlPullParser.END_DOCUMENT) { - tagName = parser.getName(); + final String tagName = parser.getName(); if (event == XmlPullParser.START_TAG) { if (tagName.equals("place")) { @@ -91,7 +88,7 @@ public List getCityResultList(String data) throws WeatherLibException { } currentTag = tagName; // Log.d("Swa", "Tag ["+tagName+"]"); - } else if (event == XmlPullParser.TEXT) { + } else if (event == XmlPullParser.TEXT && cty != null) { // We found some text. let's see the tagName to know the tag related to the text if ("woeid".equals(currentTag)) cty.setId(parser.getText()); @@ -101,7 +98,7 @@ else if ("country".equals(currentTag)) cty.setCountry(parser.getText()); // We don't want to analyze other tag at the moment - } else if (event == XmlPullParser.END_TAG) { + } else if (event == XmlPullParser.END_TAG && cty != null) { if ("place".equals(tagName)) result.add(cty); } @@ -126,44 +123,42 @@ public WeatherHourForecast getHourForecastWeather(String data) throws WeatherLib public CurrentWeather getCurrentCondition(String data) throws WeatherLibException { // Log.d("SwA", "Response ["+resp+"]"); //Log.d("App", "Data [" + data + "]"); - CurrentWeather cWeather = new CurrentWeather(); - Weather weather = new Weather(); + final Weather weather = new Weather(); try { XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); parser.setInput(new StringReader(data)); - String tagName = null; String currentTag = null; int event = parser.getEventType(); boolean isFirstDayForecast = true; while (event != XmlPullParser.END_DOCUMENT) { - tagName = parser.getName(); + final String tagName = parser.getName(); if (event == XmlPullParser.START_TAG) { if (tagName.equals("yweather:wind")) { // Iss#4 - weather.wind.setChill(Integer.parseInt(parser.getAttributeValue(null, "chill"))); - weather.wind.setDeg(Integer.parseInt(parser.getAttributeValue(null, "direction"))); - weather.wind.setSpeed(WeatherUtility.string2Float(parser.getAttributeValue(null, "speed"))); + weather.wind.setChill(WeatherUtility.parseInt(parser.getAttributeValue(null, "chill"))); + weather.wind.setDeg(WeatherUtility.parseInt(parser.getAttributeValue(null, "direction"))); + weather.wind.setSpeed(WeatherUtility.parseFloat(parser.getAttributeValue(null, "speed"))); } else if (tagName.equals("yweather:atmosphere")) { // Iss#4 - weather.currentCondition.setHumidity(Integer.parseInt(parser.getAttributeValue(null, "humidity"))); - weather.currentCondition.setVisibility(WeatherUtility.string2Float(parser.getAttributeValue(null, "visibility"))); - weather.currentCondition.setPressure(WeatherUtility.string2Float(parser.getAttributeValue(null, "pressure"))); - weather.currentCondition.setPressureTrend(Integer.parseInt(parser.getAttributeValue(null, "rising"))); + weather.currentCondition.setHumidity(WeatherUtility.parseInt(parser.getAttributeValue(null, "humidity"))); + weather.currentCondition.setVisibility(WeatherUtility.parseFloat(parser.getAttributeValue(null, "visibility"))); + weather.currentCondition.setPressure(WeatherUtility.parseFloat(parser.getAttributeValue(null, "pressure"))); + weather.currentCondition.setPressureTrend(WeatherUtility.parseInt(parser.getAttributeValue(null, "rising"))); } else if (tagName.equals("yweather:forecast")) { // Log.d("SwA", "Tag [Fore]"); if (isFirstDayForecast) { - //weather.forecast.code = Integer.parseInt(parser.getAttributeValue(null, "code")); - weather.temperature.setMinTemp(Integer.parseInt(parser.getAttributeValue(null, "low"))); - weather.temperature.setMaxTemp(Integer.parseInt(parser.getAttributeValue(null, "high"))); + //weather.forecast.code = WeatherUtility.parseInt(parser.getAttributeValue(null, "code")); + weather.temperature.setMinTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "low"))); + weather.temperature.setMaxTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "high"))); isFirstDayForecast = false; } } else if (tagName.equals("yweather:condition")) { // Log.d("SwA", "Tag [Condition]"); - weather.currentCondition.setWeatherId(Integer.parseInt(parser.getAttributeValue(null, "code"))); + weather.currentCondition.setWeatherId(WeatherUtility.parseInt(parser.getAttributeValue(null, "code"))); weather.currentCondition.setIcon("" + weather.currentCondition.getWeatherId()); // Convert the code @@ -174,18 +169,18 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio catch(Throwable t) { weather.currentCondition.setWeatherCode(WeatherCode.NOT_AVAILABLE); } - } weather.currentCondition.setCondition(parser.getAttributeValue(null, "text")); - weather.temperature.setTemp(Integer.parseInt(parser.getAttributeValue(null, "temp"))); + weather.temperature.setTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "temp"))); //result.condition.date = parser.getAttributeValue(null, "date"); } else if (tagName.equals("yweather:location")) { weather.location.setCity(parser.getAttributeValue(null, "city")); weather.location.setRegion(parser.getAttributeValue(null, "region")); weather.location.setCountry(parser.getAttributeValue(null, "country")); - } else if (tagName.equals("image")) + } else if (tagName.equals("image")) { currentTag = "image"; + } else if (tagName.equals("url")) { if (currentTag == null) { // result.imageUrl = parser.getAttributeValue(null, "src"); @@ -227,6 +222,7 @@ else if (event == XmlPullParser.TEXT) { throw new WeatherLibException(t); } + final CurrentWeather cWeather = new CurrentWeather(); cWeather.setUnit(units); cWeather.weather = weather; return cWeather; @@ -305,20 +301,16 @@ public WeatherForecast getForecastWeather(String data) throws WeatherLibExceptio XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); parser.setInput(new StringReader(data)); - String tagName = null; - String currentTag = null; - int event = parser.getEventType(); - boolean isFirstDayForecast = true; while (event != XmlPullParser.END_DOCUMENT) { - tagName = parser.getName(); + final String tagName = parser.getName(); if (event == XmlPullParser.START_TAG) { if (tagName.equals("yweather:forecast")) { DayForecast df = new DayForecast(); - df.forecastTemp.max = Integer.parseInt(parser.getAttributeValue(null, "high")); - df.forecastTemp.min = Integer.parseInt(parser.getAttributeValue(null, "low")); // Bug fixing - df.weather.currentCondition.setWeatherId(Integer.parseInt(parser.getAttributeValue(null, "code"))); + df.forecastTemp.max = WeatherUtility.parseInt(parser.getAttributeValue(null, "high")); + df.forecastTemp.min = WeatherUtility.parseInt(parser.getAttributeValue(null, "low")); // Bug fixing + df.weather.currentCondition.setWeatherId(WeatherUtility.parseInt(parser.getAttributeValue(null, "code"))); if (codeProvider != null) { try { @@ -342,9 +334,7 @@ public WeatherForecast getForecastWeather(String data) throws WeatherLibExceptio } } else if (event == XmlPullParser.END_TAG) { - if ("image".equals(currentTag)) { - currentTag = null; - } + // } event = parser.next(); } diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/util/WeatherUtility.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/util/WeatherUtility.java index c3fef4c..6cc4efa 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/util/WeatherUtility.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/util/WeatherUtility.java @@ -53,5 +53,29 @@ public static float string2Float(String value) { return Float.parseFloat(value); } + public static int parseInt(final String value){ + return parseInt(value, 0); + } + + public static int parseInt(final String value, final int defaultValue){ + try{ + return Integer.parseInt(value); + } + catch (NumberFormatException e){ + return defaultValue; + } + } + public static float parseFloat(final String value){ + return parseFloat(value, -1.0f); + } + + public static float parseFloat(final String value, final float defaultValue){ + try { + return Float.parseFloat(value); + } + catch(Exception e){ + return defaultValue; + } + } } From e6aea4b0d2b97997c9e3c2bfc47027d2da9ab44c Mon Sep 17 00:00:00 2001 From: m-rm Date: Wed, 18 Nov 2015 14:07:55 +0100 Subject: [PATCH 02/23] Cleanup YahooWeatherProvider.java --- .../yahooweather/YahooWeatherProvider.java | 60 ++++--------------- 1 file changed, 13 insertions(+), 47 deletions(-) diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java index 195bca4..5d510f0 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java @@ -84,10 +84,9 @@ public List getCityResultList(String data) throws WeatherLibException { if (tagName.equals("place")) { // place Tag Found so we create a new CityResult cty = new City.CityBuilder().build(); - // Log.d("Swa", "New City found"); } currentTag = tagName; - // Log.d("Swa", "Tag ["+tagName+"]"); + } else if (event == XmlPullParser.TEXT && cty != null) { // We found some text. let's see the tagName to know the tag related to the text if ("woeid".equals(currentTag)) @@ -106,8 +105,6 @@ else if ("country".equals(currentTag)) event = parser.next(); } } catch (Throwable t) { - //t.printStackTrace(); - // Log.e("Error in getCityList", t.getMessage()); throw new WeatherLibException(t); } @@ -121,16 +118,12 @@ public WeatherHourForecast getHourForecastWeather(String data) throws WeatherLib @Override public CurrentWeather getCurrentCondition(String data) throws WeatherLibException { - // Log.d("SwA", "Response ["+resp+"]"); - //Log.d("App", "Data [" + data + "]"); final Weather weather = new Weather(); try { XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); parser.setInput(new StringReader(data)); - String currentTag = null; - int event = parser.getEventType(); boolean isFirstDayForecast = true; while (event != XmlPullParser.END_DOCUMENT) { @@ -138,26 +131,22 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio if (event == XmlPullParser.START_TAG) { if (tagName.equals("yweather:wind")) { - // Iss#4 weather.wind.setChill(WeatherUtility.parseInt(parser.getAttributeValue(null, "chill"))); weather.wind.setDeg(WeatherUtility.parseInt(parser.getAttributeValue(null, "direction"))); weather.wind.setSpeed(WeatherUtility.parseFloat(parser.getAttributeValue(null, "speed"))); + } else if (tagName.equals("yweather:atmosphere")) { - // Iss#4 weather.currentCondition.setHumidity(WeatherUtility.parseInt(parser.getAttributeValue(null, "humidity"))); weather.currentCondition.setVisibility(WeatherUtility.parseFloat(parser.getAttributeValue(null, "visibility"))); weather.currentCondition.setPressure(WeatherUtility.parseFloat(parser.getAttributeValue(null, "pressure"))); weather.currentCondition.setPressureTrend(WeatherUtility.parseInt(parser.getAttributeValue(null, "rising"))); - } else if (tagName.equals("yweather:forecast")) { - // Log.d("SwA", "Tag [Fore]"); - if (isFirstDayForecast) { - //weather.forecast.code = WeatherUtility.parseInt(parser.getAttributeValue(null, "code")); - weather.temperature.setMinTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "low"))); - weather.temperature.setMaxTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "high"))); - isFirstDayForecast = false; - } + + } else if (tagName.equals("yweather:forecast") && isFirstDayForecast) { + weather.temperature.setMinTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "low"))); + weather.temperature.setMaxTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "high"))); + isFirstDayForecast = false; + } else if (tagName.equals("yweather:condition")) { - // Log.d("SwA", "Tag [Condition]"); weather.currentCondition.setWeatherId(WeatherUtility.parseInt(parser.getAttributeValue(null, "code"))); weather.currentCondition.setIcon("" + weather.currentCondition.getWeatherId()); @@ -173,20 +162,12 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio weather.currentCondition.setCondition(parser.getAttributeValue(null, "text")); weather.temperature.setTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "temp"))); - //result.condition.date = parser.getAttributeValue(null, "date"); + } else if (tagName.equals("yweather:location")) { weather.location.setCity(parser.getAttributeValue(null, "city")); weather.location.setRegion(parser.getAttributeValue(null, "region")); weather.location.setCountry(parser.getAttributeValue(null, "country")); - } else if (tagName.equals("image")) { - currentTag = "image"; - } - else if (tagName.equals("url")) { - if (currentTag == null) { - // result.imageUrl = parser.getAttributeValue(null, "src"); - } - } else if (tagName.equals("lastBuildDate")) { - currentTag = "update"; + } else if (tagName.equals("yweather:astronomy")) { String val = parser.getAttributeValue(null, "sunrise"); SimpleDateFormat sdf = new SimpleDateFormat("h:mm a", Locale.ENGLISH); @@ -200,23 +181,10 @@ else if (tagName.equals("url")) { java.util.Date d = sdf.parse(val); weather.location.setSunset(d.getTime()); } - } - - } else if (event == XmlPullParser.END_TAG) { - if ("image".equals(currentTag)) { - currentTag = null; - } - } - /* - else if (event == XmlPullParser.TEXT) { - if ("update".equals(currentTag)) - //result.lastUpdate = parser.getText(); } - */ event = parser.next(); } - } catch (Throwable t) { t.printStackTrace(); throw new WeatherLibException(t); @@ -231,8 +199,9 @@ else if (event == XmlPullParser.TEXT) { @Override public String getQueryCityURL(String cityNamePattern) throws ApiKeyRequiredException { - if (config.ApiKey == null) + if (config.ApiKey == null) { throw new ApiKeyRequiredException(); + } // We remove spaces in cityName cityNamePattern = cityNamePattern.replaceAll(" ", "%20"); @@ -324,17 +293,14 @@ public WeatherForecast getForecastWeather(String data) throws WeatherLibExceptio df.weather.currentCondition.setCondition(parser.getAttributeValue(null, "text")); df.weather.currentCondition.setIcon("" + df.weather.currentCondition.getWeatherId()); forecast.addForecast(df); + } else if (tagName.equals("yweather:units")) { - // Log.d("SwA", "Tag [units]"); units.tempUnit = "°" + parser.getAttributeValue(null, "temperature"); units.pressureUnit = parser.getAttributeValue(null, "pressure"); units.distanceUnit = parser.getAttributeValue(null, "distance"); units.speedUnit = parser.getAttributeValue(null, "speed"); forecast.setUnit(units); } - - } else if (event == XmlPullParser.END_TAG) { - // } event = parser.next(); } From 4b6af178df808626053c03f46308f821dad3fc0c Mon Sep 17 00:00:00 2001 From: m-rm Date: Wed, 18 Nov 2015 14:53:20 +0100 Subject: [PATCH 03/23] Unify parsing of current weather and forecast --- .../yahooweather/YahooWeatherProvider.java | 169 +++++++++--------- 1 file changed, 86 insertions(+), 83 deletions(-) diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java index 5d510f0..5f2428b 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java @@ -16,6 +16,7 @@ package com.survivingwithandroid.weather.lib.provider.yahooweather; import android.location.Location; +import android.util.Pair; import com.survivingwithandroid.weather.lib.WeatherCode; import com.survivingwithandroid.weather.lib.WeatherConfig; @@ -118,82 +119,7 @@ public WeatherHourForecast getHourForecastWeather(String data) throws WeatherLib @Override public CurrentWeather getCurrentCondition(String data) throws WeatherLibException { - final Weather weather = new Weather(); - - try { - XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); - parser.setInput(new StringReader(data)); - - int event = parser.getEventType(); - boolean isFirstDayForecast = true; - while (event != XmlPullParser.END_DOCUMENT) { - final String tagName = parser.getName(); - - if (event == XmlPullParser.START_TAG) { - if (tagName.equals("yweather:wind")) { - weather.wind.setChill(WeatherUtility.parseInt(parser.getAttributeValue(null, "chill"))); - weather.wind.setDeg(WeatherUtility.parseInt(parser.getAttributeValue(null, "direction"))); - weather.wind.setSpeed(WeatherUtility.parseFloat(parser.getAttributeValue(null, "speed"))); - - } else if (tagName.equals("yweather:atmosphere")) { - weather.currentCondition.setHumidity(WeatherUtility.parseInt(parser.getAttributeValue(null, "humidity"))); - weather.currentCondition.setVisibility(WeatherUtility.parseFloat(parser.getAttributeValue(null, "visibility"))); - weather.currentCondition.setPressure(WeatherUtility.parseFloat(parser.getAttributeValue(null, "pressure"))); - weather.currentCondition.setPressureTrend(WeatherUtility.parseInt(parser.getAttributeValue(null, "rising"))); - - } else if (tagName.equals("yweather:forecast") && isFirstDayForecast) { - weather.temperature.setMinTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "low"))); - weather.temperature.setMaxTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "high"))); - isFirstDayForecast = false; - - } else if (tagName.equals("yweather:condition")) { - weather.currentCondition.setWeatherId(WeatherUtility.parseInt(parser.getAttributeValue(null, "code"))); - weather.currentCondition.setIcon("" + weather.currentCondition.getWeatherId()); - - // Convert the code - if (codeProvider != null) { - try { - weather.currentCondition.setWeatherCode(codeProvider.getWeatherCode(String.valueOf(weather.currentCondition.getWeatherId()))); - } - catch(Throwable t) { - weather.currentCondition.setWeatherCode(WeatherCode.NOT_AVAILABLE); - } - } - - weather.currentCondition.setCondition(parser.getAttributeValue(null, "text")); - weather.temperature.setTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "temp"))); - - } else if (tagName.equals("yweather:location")) { - weather.location.setCity(parser.getAttributeValue(null, "city")); - weather.location.setRegion(parser.getAttributeValue(null, "region")); - weather.location.setCountry(parser.getAttributeValue(null, "country")); - - } else if (tagName.equals("yweather:astronomy")) { - String val = parser.getAttributeValue(null, "sunrise"); - SimpleDateFormat sdf = new SimpleDateFormat("h:mm a", Locale.ENGLISH); - if (val != null) { - java.util.Date d = sdf.parse(val); - weather.location.setSunrise(d.getTime()); - } - - val = parser.getAttributeValue(null, "sunset"); - if (val != null) { - java.util.Date d = sdf.parse(val); - weather.location.setSunset(d.getTime()); - } - } - } - event = parser.next(); - } - } catch (Throwable t) { - t.printStackTrace(); - throw new WeatherLibException(t); - } - - final CurrentWeather cWeather = new CurrentWeather(); - cWeather.setUnit(units); - cWeather.weather = weather; - return cWeather; + return getWeather(data).first; } @Override @@ -263,24 +189,48 @@ public String getQueryHourForecastWeatherURL(String cityId) throws ApiKeyRequire @Override public WeatherForecast getForecastWeather(String data) throws WeatherLibException { + return getWeather(data).second; + } - WeatherForecast forecast = new WeatherForecast(); + private Pair getWeather(final String data) throws WeatherLibException{ + final Weather current = new Weather(); + final WeatherForecast forecast = new WeatherForecast(); try { XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); parser.setInput(new StringReader(data)); int event = parser.getEventType(); + boolean isFirstDayForecast = true; + String text = null; + while (event != XmlPullParser.END_DOCUMENT) { final String tagName = parser.getName(); if (event == XmlPullParser.START_TAG) { - if (tagName.equals("yweather:forecast")) { + if (tagName.equals("yweather:wind")) { + current.wind.setChill(WeatherUtility.parseInt(parser.getAttributeValue(null, "chill"))); + current.wind.setDeg(WeatherUtility.parseInt(parser.getAttributeValue(null, "direction"))); + current.wind.setSpeed(WeatherUtility.parseFloat(parser.getAttributeValue(null, "speed"))); + + } else if (tagName.equals("yweather:atmosphere")) { + current.currentCondition.setHumidity(WeatherUtility.parseInt(parser.getAttributeValue(null, "humidity"))); + current.currentCondition.setVisibility(WeatherUtility.parseFloat(parser.getAttributeValue(null, "visibility"))); + current.currentCondition.setPressure(WeatherUtility.parseFloat(parser.getAttributeValue(null, "pressure"))); + current.currentCondition.setPressureTrend(WeatherUtility.parseInt(parser.getAttributeValue(null, "rising"))); + + } else if (tagName.equals("yweather:forecast")) { + if(isFirstDayForecast) { + current.temperature.setMinTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "low"))); + current.temperature.setMaxTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "high"))); + isFirstDayForecast = false; + } + DayForecast df = new DayForecast(); df.forecastTemp.max = WeatherUtility.parseInt(parser.getAttributeValue(null, "high")); df.forecastTemp.min = WeatherUtility.parseInt(parser.getAttributeValue(null, "low")); // Bug fixing df.weather.currentCondition.setWeatherId(WeatherUtility.parseInt(parser.getAttributeValue(null, "code"))); - + df.weather.location = current.location; if (codeProvider != null) { try { df.weather.currentCondition.setWeatherCode(codeProvider.getWeatherCode(String.valueOf(df.weather.currentCondition.getWeatherId()))); @@ -294,24 +244,77 @@ public WeatherForecast getForecastWeather(String data) throws WeatherLibExceptio df.weather.currentCondition.setIcon("" + df.weather.currentCondition.getWeatherId()); forecast.addForecast(df); + } else if (tagName.equals("yweather:condition")) { + current.currentCondition.setWeatherId(WeatherUtility.parseInt(parser.getAttributeValue(null, "code"))); + current.currentCondition.setIcon("" + current.currentCondition.getWeatherId()); + + // Convert the code + if (codeProvider != null) { + try { + current.currentCondition.setWeatherCode(codeProvider.getWeatherCode(String.valueOf(current.currentCondition.getWeatherId()))); + } + catch(Throwable t) { + current.currentCondition.setWeatherCode(WeatherCode.NOT_AVAILABLE); + } + } + + current.currentCondition.setCondition(parser.getAttributeValue(null, "text")); + current.temperature.setTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "temp"))); + + } else if (tagName.equals("yweather:location")) { + current.location.setCity(parser.getAttributeValue(null, "city")); + current.location.setRegion(parser.getAttributeValue(null, "region")); + current.location.setCountry(parser.getAttributeValue(null, "country")); + + } else if (tagName.equals("yweather:astronomy")) { + String val = parser.getAttributeValue(null, "sunrise"); + SimpleDateFormat sdf = new SimpleDateFormat("h:mm a", Locale.ENGLISH); + if (val != null) { + java.util.Date d = sdf.parse(val); + current.location.setSunrise(d.getTime()); + } + + val = parser.getAttributeValue(null, "sunset"); + if (val != null) { + java.util.Date d = sdf.parse(val); + current.location.setSunset(d.getTime()); + } } else if (tagName.equals("yweather:units")) { units.tempUnit = "°" + parser.getAttributeValue(null, "temperature"); units.pressureUnit = parser.getAttributeValue(null, "pressure"); units.distanceUnit = parser.getAttributeValue(null, "distance"); units.speedUnit = parser.getAttributeValue(null, "speed"); - forecast.setUnit(units); } } + else if (event == XmlPullParser.TEXT) { + text = parser.getText(); + } + else if (event == XmlPullParser.END_TAG) { + if (tagName.equals("geo:lat")){ + current.location.setLatitude(WeatherUtility.parseFloat(text)); + } else if (tagName.equals("geo:long")){ + current.location.setLongitude(WeatherUtility.parseFloat(text)); + } + } + event = parser.next(); } - } catch (Throwable t) { t.printStackTrace(); throw new WeatherLibException(t); } - return forecast; - } + // Prepare the current weather for return + final CurrentWeather currentWeather = new CurrentWeather(); + currentWeather.setUnit(units); + currentWeather.weather = current; + + // Prepare forecast for return + forecast.setUnit(units); + + // Assemble and return + return new Pair(currentWeather, forecast); + } @Override public void setConfig(WeatherConfig config) { From 0ed1647a2654dff5b846b959b7b28d2a4176b5d8 Mon Sep 17 00:00:00 2001 From: m-rm Date: Mon, 18 Apr 2016 14:47:36 +0200 Subject: [PATCH 04/23] Adaptions to recent Yahoo weather changes --- .../yahooweather/YahooWeatherProvider.java | 37 +++++++++++-------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java index 5f2428b..5f7d2db 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java @@ -40,6 +40,9 @@ import org.xmlpull.v1.XmlPullParserFactory; import java.io.StringReader; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; @@ -48,8 +51,8 @@ public class YahooWeatherProvider implements IWeatherProvider { - private static String YAHOO_GEO_URL = "http://where.yahooapis.com/v1"; - private static String YAHOO_WEATHER_URL = "http://weather.yahooapis.com/forecastrss"; + private static final String YAHOO_GEO_URL = "http://where.yahooapis.com/v1"; + private static final String YAHOO_WEATHER_URL = "https://query.yahooapis.com/v1/public/yql"; private static final String YAHOO_IMG_URL = "http://l.yimg.com/a/i/us/we/52/"; private WeatherConfig config; @@ -124,7 +127,6 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio @Override public String getQueryCityURL(String cityNamePattern) throws ApiKeyRequiredException { - if (config.ApiKey == null) { throw new ApiKeyRequiredException(); } @@ -349,22 +351,27 @@ public String getQueryCurrentWeatherURL(WeatherRequest request) throws ApiKeyReq if (request.getCityId() == null) throw new UnsupportedOperationException("Can't use lon and lat"); - return YAHOO_WEATHER_URL + "?w=" + request.getCityId() - + "&u=" + (WeatherUtility.isMetric(config.unitSystem) ? "c" : "f") - + "&d=1"; + // YQL query https://developer.yahoo.com/weather/ + String query = "select * from weather.forecast where woeid={0} AND u=''{1}''"; + + // Replace placeholders + query = MessageFormat.format(query, + request.getCityId(), + WeatherUtility.isMetric(config.unitSystem) ? "c" : "f"); + + try { + query = URLEncoder.encode(query, "UTF-8"); + }catch (UnsupportedEncodingException e){ + throw new RuntimeException("Url encoding failed", e); + } + + return YAHOO_WEATHER_URL + "?q=" + query + "&format=xml"; } @Override public String getQueryForecastWeatherURL(WeatherRequest request) throws ApiKeyRequiredException { - if (config.ApiKey == null) - throw new ApiKeyRequiredException(); - - if (request.getCityId() == null) - throw new UnsupportedOperationException("Can't use lon and lat"); - - return YAHOO_WEATHER_URL + "?w=" + request.getCityId() - + "&u=" + (WeatherUtility.isMetric(config.unitSystem) ? "c" : "f") - + "&d=" + config.numDays; + // The new API always returns the current day + 9 forecast days. So we can use the same URL. + return getQueryCurrentWeatherURL(request); } @Override From b76b89d021cc54f60204a22e36b98d3b5f193c61 Mon Sep 17 00:00:00 2001 From: m-rm Date: Mon, 5 Sep 2016 16:51:26 +0200 Subject: [PATCH 05/23] Adaptions to Yahoo GeoPlanet shutdown --- .../yahooweather/YahooWeatherProvider.java | 32 +++++++++++-------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java index 5f7d2db..d7931c4 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java @@ -51,7 +51,6 @@ public class YahooWeatherProvider implements IWeatherProvider { - private static final String YAHOO_GEO_URL = "http://where.yahooapis.com/v1"; private static final String YAHOO_WEATHER_URL = "https://query.yahooapis.com/v1/public/yql"; private static final String YAHOO_IMG_URL = "http://l.yimg.com/a/i/us/we/52/"; @@ -127,13 +126,24 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio @Override public String getQueryCityURL(String cityNamePattern) throws ApiKeyRequiredException { - if (config.ApiKey == null) { - throw new ApiKeyRequiredException(); + // Wildcard to enable completion + return getQueryCityURLFromString(cityNamePattern + "*"); + } + + private String getQueryCityURLFromString(String text){ + // YQL query https://developer.yahoo.com/weather/ + String query = "SELECT * FROM geo.places WHERE text=\"{0}\" AND placeTypeName.code = 7"; + + // Replace placeholders + query = MessageFormat.format(query, text); + + try { + query = URLEncoder.encode(query, "UTF-8"); + }catch (UnsupportedEncodingException e){ + throw new RuntimeException("Url encoding failed", e); } - // We remove spaces in cityName - cityNamePattern = cityNamePattern.replaceAll(" ", "%20"); - return YAHOO_GEO_URL + "/places.q('" + cityNamePattern + "%2A');count=" + config.maxResult + "?appid=" + config.ApiKey; + return YAHOO_WEATHER_URL + "?q=" + query + "&format=xml"; } /* @@ -163,18 +173,12 @@ public HistoricalWeather getHistoricalWeather(String data) throws WeatherLibExce @Override public String getQueryCityURLByLocation(Location location) throws ApiKeyRequiredException { - if (config.ApiKey == null) - throw new ApiKeyRequiredException(); - - return YAHOO_GEO_URL + "/places.q('" + location.getLatitude() + "," + location.getLongitude() + "')?appid=" + config.ApiKey; + return getQueryCityURLByCoord(location.getLatitude(), location.getLongitude()); } @Override public String getQueryCityURLByCoord(double lon, double lat) throws ApiKeyRequiredException { - if (config.ApiKey == null) - throw new ApiKeyRequiredException(); - - return YAHOO_GEO_URL + "/places.q('" + lat + "," + lon + "')?appid=" + config.ApiKey; + return getQueryCityURLFromString(lon + ", " + lat); } @Override From 9c4170b71892d552049eb6254e5db929d2b4823f Mon Sep 17 00:00:00 2001 From: m-rm Date: Wed, 11 Jan 2017 15:02:29 +0100 Subject: [PATCH 06/23] Fix WeatherUnderground parsing exception --- .../lib/provider/wunderground/WeatherUndergroundProvider.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java index 95e19d9..d96b026 100644 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java @@ -114,7 +114,7 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio String trend = getString("pressure_trend", jObj); int trendVal = -1; - if ("-".equals(trend)) + if ("-".equals(trend) || "+".equals(trend)) trendVal = 0; else trendVal = Integer.parseInt(trend); From 34c43469f0a76a15a1e6bf751d2c87bd9ebeb013 Mon Sep 17 00:00:00 2001 From: m-rm Date: Wed, 11 Jan 2017 15:39:39 +0100 Subject: [PATCH 07/23] Fix Java 8 build --- build.gradle | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/build.gradle b/build.gradle index 074a2fc..6715c8b 100644 --- a/build.gradle +++ b/build.gradle @@ -14,6 +14,14 @@ def isReleaseBuild() { return version.contains("SNAPSHOT") == false } +if (JavaVersion.current().isJava8Compatible()) { + allprojects { + tasks.withType(Javadoc) { + options.addStringOption('Xdoclint:none', '-quiet') + } + } +} + allprojects { version = VERSION_NAME group = GROUP From 5d444c7a7bce574a55b48cd05142a95dfb7986c2 Mon Sep 17 00:00:00 2001 From: m-rm Date: Wed, 11 Jan 2017 15:44:14 +0100 Subject: [PATCH 08/23] Upgrade to newest Gradle and Android plugin version --- build.gradle | 5 ++--- demo/build.gradle | 1 - demo15/build.gradle | 1 - gradle/wrapper/gradle-wrapper.properties | 2 +- 4 files changed, 3 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index 6715c8b..115ef10 100644 --- a/build.gradle +++ b/build.gradle @@ -2,11 +2,10 @@ buildscript { repositories { - mavenCentral() + jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:1.0.0' - classpath 'com.jakewharton.sdkmanager:gradle-plugin:0.12.0' + classpath 'com.android.tools.build:gradle:2.2.3' } } diff --git a/demo/build.gradle b/demo/build.gradle index f40ac01..db63582 100644 --- a/demo/build.gradle +++ b/demo/build.gradle @@ -1,4 +1,3 @@ -apply plugin: 'android-sdk-manager' apply plugin: 'android' diff --git a/demo15/build.gradle b/demo15/build.gradle index eb71c23..9971944 100644 --- a/demo15/build.gradle +++ b/demo15/build.gradle @@ -1,4 +1,3 @@ -apply plugin: 'android-sdk-manager' apply plugin: 'android' repositories { diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 0c71e76..eaba301 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip From b00096b8a1d2fd881ce1024ed64c900d6f2bb326 Mon Sep 17 00:00:00 2001 From: m-rm Date: Wed, 11 Jan 2017 15:49:57 +0100 Subject: [PATCH 09/23] Get latitude and longitude from City class --- .../com/survivingwithandroid/weather/lib/model/City.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/model/City.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/model/City.java index 163af16..c4d0c31 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/model/City.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/model/City.java @@ -107,6 +107,14 @@ public void setRegion(String region) { this.region = region; } + public double getLatitude(){ + return lat; + } + + public double getLongitude(){ + return lon; + } + public String toString(){ return this.name + ", " + this.country; } From e0901393f27ec760b1237551e5d20d39d671cd40 Mon Sep 17 00:00:00 2001 From: m-rm Date: Wed, 11 Jan 2017 16:03:33 +0100 Subject: [PATCH 10/23] Upgrading Android build tools --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 115ef10..58ce7f5 100644 --- a/build.gradle +++ b/build.gradle @@ -32,7 +32,7 @@ allprojects { ext { compileSdkVersion = 19 - buildToolsVersion = "21.0.1" + buildToolsVersion = "25.0.2" } From 6293f996c787709774a9877605b948f7599d68f3 Mon Sep 17 00:00:00 2001 From: m-rm Date: Wed, 11 Jan 2017 16:45:33 +0100 Subject: [PATCH 11/23] Publish to local Nexus for internal use --- OkHttpClient/build.gradle | 3 +- gradle.properties | 16 +++--- lib/build.gradle | 3 +- nexus_push.gradle | 108 ++++++++++++++++++++++++++++++++++++++ volleyclient/build.gradle | 3 +- 5 files changed, 123 insertions(+), 10 deletions(-) create mode 100644 nexus_push.gradle diff --git a/OkHttpClient/build.gradle b/OkHttpClient/build.gradle index a0e129e..7bcf6f0 100644 --- a/OkHttpClient/build.gradle +++ b/OkHttpClient/build.gradle @@ -54,4 +54,5 @@ task makeJar(type: Copy) { } makeJar.dependsOn(clearJar, build) -apply from: '../maven_push.gradle' \ No newline at end of file +//apply from: '../maven_push.gradle' +apply from: '../nexus_push.gradle' \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index ab3d441..83ea41e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,14 +1,16 @@ -VERSION_NAME=1.6.0 +VERSION_NAME=1.6.1 VERSION_CODE=19 -GROUP=com.survivingwithandroid +GROUP=at.ac.ait.hbs.android POM_DESCRIPTION=Android Weather Lib -POM_URL=https://github.com/survivingwithandroid/WeatherLib -POM_SCM_URL=https://github.com/survivingwithandroid/WeatherLib -POM_SCM_CONNECTION=scm:git@github.com:survivingwithandroid/weatherlib.git -POM_SCM_DEV_CONNECTION=scm:git@github.com:survivingwithandroid/weatherlib.git +POM_URL=https://github.com/m-rm/WeatherLib +POM_SCM_URL=https://github.com/m-rm/WeatherLib +POM_SCM_CONNECTION=scm:git@github.com:m-rm/weatherlib.git +POM_SCM_DEV_CONNECTION=scm:git@github.com:m-rm/weatherlib.git POM_LICENCE_NAME=The Apache Software License, Version 2.0 POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt POM_LICENCE_DIST=repo POM_DEVELOPER_ID=survivingwithandroid -POM_DEVELOPER_NAME=Francesco Azzola \ No newline at end of file +POM_DEVELOPER_NAME=Francesco Azzola +POM_DEVELOPER2_ID=m-rm +POM_DEVELOPER2_NAME=M-RM \ No newline at end of file diff --git a/lib/build.gradle b/lib/build.gradle index ce81efe..137bb8e 100644 --- a/lib/build.gradle +++ b/lib/build.gradle @@ -52,4 +52,5 @@ task makeJar(type: Copy) { makeJar.dependsOn(clearJar, build) -apply from: '../maven_push.gradle' \ No newline at end of file +//apply from: '../maven_push.gradle' +apply from: '../nexus_push.gradle' \ No newline at end of file diff --git a/nexus_push.gradle b/nexus_push.gradle new file mode 100644 index 0000000..900af0a --- /dev/null +++ b/nexus_push.gradle @@ -0,0 +1,108 @@ +apply plugin: 'maven' +//apply plugin: 'signing' + + +def sonatypeRepositoryUrl +if (isReleaseBuild()) { + println 'RELEASE BUILD' + sonatypeRepositoryUrl = hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL + : "http://nexus.arcsmed.at/content/repositories/android/" +/* +} else { + println 'SNAPSHOT BUILD' + sonatypeRepositoryUrl = hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL + : "https://oss.sonatype.org/content/repositories/snapshots/" + +*/ +} + +def getRepositoryUsername() { + return hasProperty('nexusUsername') ? nexusUsername : "" +} + +def getRepositoryPassword() { + return hasProperty('nexusPassword') ? nexusPassword : "" +} + +afterEvaluate { project -> + uploadArchives { + repositories { + mavenDeployer { + //beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } + + pom.artifactId = POM_ARTIFACT_ID + + repository(url: sonatypeRepositoryUrl) { + authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) + } + + pom.project { + name POM_NAME + packaging POM_PACKAGING + description POM_DESCRIPTION + url POM_URL + + scm { + url POM_SCM_URL + connection POM_SCM_CONNECTION + developerConnection POM_SCM_DEV_CONNECTION + } + + licenses { + license { + name POM_LICENCE_NAME + url POM_LICENCE_URL + distribution POM_LICENCE_DIST + } + } + + developers { + developer { + id POM_DEVELOPER_ID + name POM_DEVELOPER_NAME + } + developer { + id POM_DEVELOPER2_ID + name POM_DEVELOPER2_NAME + } + } + } + } + } + } + + /* + signing { + required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } + sign configurations.archives + } + */ + + task androidJavadocs(type: Javadoc) { + //source = android.sourceSets.main.allJava + options { + linksOffline "http://d.android.com/reference", "${android.sdkDirectory}/docs/reference" + } + source = android.sourceSets.main.java.sourceFiles + //classpath += project.files(android.plugin.getRuntimeJarList().join(File.pathSeparator)) + classpath += project.files(project.android.getBootClasspath().join(File.pathSeparator)) + } + + task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { + classifier = 'javadoc' + //basename = artifact_id + from androidJavadocs.destinationDir + } + + task androidSourcesJar(type: Jar) { + classifier = 'sources' + //basename = artifact_id + //from android.sourceSets.main.allSource + from android.sourceSets.main.java.sourceFiles + } + + artifacts { + archives androidSourcesJar + archives androidJavadocsJar + } +} \ No newline at end of file diff --git a/volleyclient/build.gradle b/volleyclient/build.gradle index 5690780..6255fcd 100644 --- a/volleyclient/build.gradle +++ b/volleyclient/build.gradle @@ -56,4 +56,5 @@ task makeJar(type: Copy) { makeJar.dependsOn(clearJar, build) -apply from: '../maven_push.gradle' \ No newline at end of file +//apply from: '../maven_push.gradle' +apply from: '../nexus_push.gradle' \ No newline at end of file From bf3013a0221644cdcf27a9aa583549766354a465 Mon Sep 17 00:00:00 2001 From: m-rm Date: Thu, 12 Jan 2017 15:29:58 +0100 Subject: [PATCH 12/23] Using new android plugin names --- OkHttpClient/build.gradle | 2 +- demo/build.gradle | 2 +- demo15/build.gradle | 2 +- lib/build.gradle | 2 +- volleyclient/build.gradle | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/OkHttpClient/build.gradle b/OkHttpClient/build.gradle index 7bcf6f0..7335a6d 100644 --- a/OkHttpClient/build.gradle +++ b/OkHttpClient/build.gradle @@ -1,4 +1,4 @@ -apply plugin: 'android-library' +apply plugin: 'com.android.library' android { compileSdkVersion rootProject.ext.compileSdkVersion diff --git a/demo/build.gradle b/demo/build.gradle index db63582..110d5d0 100644 --- a/demo/build.gradle +++ b/demo/build.gradle @@ -1,4 +1,4 @@ -apply plugin: 'android' +apply plugin: 'com.android.application' android { diff --git a/demo15/build.gradle b/demo15/build.gradle index 9971944..a300ad0 100644 --- a/demo15/build.gradle +++ b/demo15/build.gradle @@ -1,4 +1,4 @@ -apply plugin: 'android' +apply plugin: 'com.android.application' repositories { mavenCentral() diff --git a/lib/build.gradle b/lib/build.gradle index 137bb8e..acc2f5b 100644 --- a/lib/build.gradle +++ b/lib/build.gradle @@ -1,5 +1,5 @@ // Maven -apply plugin: 'android-library' +apply plugin: 'com.android.library' android { compileSdkVersion rootProject.ext.compileSdkVersion diff --git a/volleyclient/build.gradle b/volleyclient/build.gradle index 6255fcd..d8de5dd 100644 --- a/volleyclient/build.gradle +++ b/volleyclient/build.gradle @@ -1,4 +1,4 @@ -apply plugin: 'android-library' +apply plugin: 'com.android.library' android { compileSdkVersion rootProject.ext.compileSdkVersion From d2cbb64806b444cb277e8dc365a81859fe83f724 Mon Sep 17 00:00:00 2001 From: m-rm Date: Thu, 12 Jan 2017 16:36:03 +0100 Subject: [PATCH 13/23] Update to new publish plugin --- build.gradle | 6 +- gradle/wrapper/gradle-wrapper.properties | 3 +- nexus_push.gradle | 156 +++++++++-------------- 3 files changed, 67 insertions(+), 98 deletions(-) diff --git a/build.gradle b/build.gradle index 58ce7f5..b49ed2e 100644 --- a/build.gradle +++ b/build.gradle @@ -3,9 +3,13 @@ buildscript { repositories { jcenter() + maven { + url "https://plugins.gradle.org/m2/" + } } dependencies { - classpath 'com.android.tools.build:gradle:2.2.3' + classpath 'com.android.tools.build:gradle:2.1.2' // Do not upgrade because it will break the maven-settings plugin (or check if the plugin was updated) + classpath 'net.linguica.gradle:maven-settings-plugin:0.5' } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index eaba301..44cd6cb 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip +# Do not upgrade because it will break the maven-settings plugin (or check if the plugin was updated) +distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip diff --git a/nexus_push.gradle b/nexus_push.gradle index 900af0a..9e4a6e6 100644 --- a/nexus_push.gradle +++ b/nexus_push.gradle @@ -1,108 +1,72 @@ -apply plugin: 'maven' -//apply plugin: 'signing' - - -def sonatypeRepositoryUrl -if (isReleaseBuild()) { - println 'RELEASE BUILD' - sonatypeRepositoryUrl = hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL - : "http://nexus.arcsmed.at/content/repositories/android/" -/* -} else { - println 'SNAPSHOT BUILD' - sonatypeRepositoryUrl = hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL - : "https://oss.sonatype.org/content/repositories/snapshots/" - -*/ -} - -def getRepositoryUsername() { - return hasProperty('nexusUsername') ? nexusUsername : "" -} - -def getRepositoryPassword() { - return hasProperty('nexusPassword') ? nexusPassword : "" -} - -afterEvaluate { project -> - uploadArchives { - repositories { - mavenDeployer { - //beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } - - pom.artifactId = POM_ARTIFACT_ID - - repository(url: sonatypeRepositoryUrl) { - authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) - } - - pom.project { - name POM_NAME - packaging POM_PACKAGING - description POM_DESCRIPTION - url POM_URL - - scm { - url POM_SCM_URL - connection POM_SCM_CONNECTION - developerConnection POM_SCM_DEV_CONNECTION - } +apply plugin: 'net.linguica.maven-settings' +apply plugin: 'maven-publish' + +publishing { + publications { + maven(MavenPublication) { + artifactId = POM_ARTIFACT_ID + + pom.withXml { + def root = asNode() + root.appendNode('name', POM_NAME) + root.appendNode('description', POM_DESCRIPTION) + root.appendNode('url', POM_URL) + + def scm = root.appendNode('scm') + scm.appendNode('url', POM_SCM_URL) + scm.appendNode('connection', POM_SCM_CONNECTION) + scm.appendNode('developerConnection', POM_SCM_DEV_CONNECTION) + + def license = root.appendNode('licenses').appendNode('license') + license.appendNode('name', POM_LICENCE_NAME) + license.appendNode('url', POM_LICENCE_URL) + license.appendNode('distribution', POM_LICENCE_DIST) + + def developers = root.appendNode('developers') + def developer = developers.appendNode('developer') + developer.appendNode('id', POM_DEVELOPER_ID) + developer.appendNode('name', POM_DEVELOPER_NAME) + + developer = developers.appendNode('developer') + developer.appendNode('id', POM_DEVELOPER2_ID) + developer.appendNode('name', POM_DEVELOPER2_NAME) + } - licenses { - license { - name POM_LICENCE_NAME - url POM_LICENCE_URL - distribution POM_LICENCE_DIST - } - } + def files = new FileNameFinder().getFileNames("$buildDir/outputs/aar/", "*-release.aar"); - developers { - developer { - id POM_DEVELOPER_ID - name POM_DEVELOPER_NAME - } - developer { - id POM_DEVELOPER2_ID - name POM_DEVELOPER2_NAME - } - } - } - } + artifact androidSourcesJar + artifact androidJavadocsJar + artifact files[0] } } - /* - signing { - required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } - sign configurations.archives - } - */ - - task androidJavadocs(type: Javadoc) { - //source = android.sourceSets.main.allJava - options { - linksOffline "http://d.android.com/reference", "${android.sdkDirectory}/docs/reference" + repositories { + maven { + name "at.ac.ait.hbs.android" + url "http://nexus.arcsmed.at/content/repositories/android/" } - source = android.sourceSets.main.java.sourceFiles - //classpath += project.files(android.plugin.getRuntimeJarList().join(File.pathSeparator)) - classpath += project.files(project.android.getBootClasspath().join(File.pathSeparator)) } +} - task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { - classifier = 'javadoc' - //basename = artifact_id - from androidJavadocs.destinationDir +task androidJavadocs(type: Javadoc) { + //source = android.sourceSets.main.allJava + options { + linksOffline "http://d.android.com/reference", "${android.sdkDirectory}/docs/reference" } + source = android.sourceSets.main.java.sourceFiles + //classpath += project.files(android.plugin.getRuntimeJarList().join(File.pathSeparator)) + classpath += project.files(project.android.getBootClasspath().join(File.pathSeparator)) +} - task androidSourcesJar(type: Jar) { - classifier = 'sources' - //basename = artifact_id - //from android.sourceSets.main.allSource - from android.sourceSets.main.java.sourceFiles - } +task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { + classifier = 'javadoc' + //basename = artifact_id + from androidJavadocs.destinationDir +} - artifacts { - archives androidSourcesJar - archives androidJavadocsJar - } +task androidSourcesJar(type: Jar) { + classifier = 'sources' + //basename = artifact_id + //from android.sourceSets.main.allSource + from android.sourceSets.main.java.sourceFiles } \ No newline at end of file From bfff93270c6c567224d4a9274a550834067e9e64 Mon Sep 17 00:00:00 2001 From: m-rm Date: Fri, 13 Jan 2017 13:01:49 +0100 Subject: [PATCH 14/23] Fixing some error produced by android-reporting --- nexus_push.gradle | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/nexus_push.gradle b/nexus_push.gradle index 9e4a6e6..99876e2 100644 --- a/nexus_push.gradle +++ b/nexus_push.gradle @@ -32,7 +32,19 @@ publishing { developer.appendNode('name', POM_DEVELOPER2_NAME) } - def files = new FileNameFinder().getFileNames("$buildDir/outputs/aar/", "*-release.aar"); + def folder = new File("$buildDir/outputs/aar/") + + if(!folder.exists()){ + println "Output folder not found, skipping publish" + return; + } + + def files = new FileNameFinder().getFileNames(folder.absolutePath, "*-release.aar"); + + if(files.size() == 0){ + println "No AAR file found, skipping publish" + return; + } artifact androidSourcesJar artifact androidJavadocsJar From bf50cbf5b0e6d63786499497dd45c5de9bfa53c8 Mon Sep 17 00:00:00 2001 From: m-rm Date: Fri, 13 Jan 2017 13:24:27 +0100 Subject: [PATCH 15/23] Use unofficial snapshot of maven-settings-plugin that support Android Gradle plugin > 2.1.2 --- build.gradle | 6 +++--- gradle/wrapper/gradle-wrapper.properties | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index b49ed2e..8f11ea8 100644 --- a/build.gradle +++ b/build.gradle @@ -4,12 +4,12 @@ buildscript { repositories { jcenter() maven { - url "https://plugins.gradle.org/m2/" + url "http://nexus.arcsmed.at/content/repositories/public-snapshots/" } } dependencies { - classpath 'com.android.tools.build:gradle:2.1.2' // Do not upgrade because it will break the maven-settings plugin (or check if the plugin was updated) - classpath 'net.linguica.gradle:maven-settings-plugin:0.5' + classpath 'com.android.tools.build:gradle:2.2.3' // Do not upgrade because it will break the maven-settings plugin (or check if the plugin was updated) + classpath 'net.linguica.gradle:maven-settings-plugin:0.7.0-SNAPSHOT' } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 44cd6cb..543a4e9 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -4,4 +4,4 @@ distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists # Do not upgrade because it will break the maven-settings plugin (or check if the plugin was updated) -distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip From c9cfa18a55c04f055d7aee9d0d768a24c72c0e3c Mon Sep 17 00:00:00 2001 From: m-rm Date: Fri, 13 Jan 2017 13:34:22 +0100 Subject: [PATCH 16/23] Use unofficial snapshot of maven-settings-plugin that support Android Gradle plugin > 2.1.2 --- build.gradle | 4 ++-- gradle/wrapper/gradle-wrapper.properties | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/build.gradle b/build.gradle index 8f11ea8..0cfa4b9 100644 --- a/build.gradle +++ b/build.gradle @@ -8,8 +8,8 @@ buildscript { } } dependencies { - classpath 'com.android.tools.build:gradle:2.2.3' // Do not upgrade because it will break the maven-settings plugin (or check if the plugin was updated) - classpath 'net.linguica.gradle:maven-settings-plugin:0.7.0-SNAPSHOT' + classpath 'com.android.tools.build:gradle:2.2.3' + classpath 'net.linguica.gradle:maven-settings-plugin:0.7.0-SNAPSHOT' // Use official one when available } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 543a4e9..eaba301 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,5 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -# Do not upgrade because it will break the maven-settings plugin (or check if the plugin was updated) distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip From 13827b73c86e82092cb8a5e2763823c70a15cb1b Mon Sep 17 00:00:00 2001 From: m-rm Date: Mon, 16 Jan 2017 14:22:53 +0100 Subject: [PATCH 17/23] Fix deployment --- build.gradle | 5 -- nexus_push.gradle | 135 ++++++++++++++++++++++++---------------------- 2 files changed, 70 insertions(+), 70 deletions(-) diff --git a/build.gradle b/build.gradle index 0cfa4b9..7c5436a 100644 --- a/build.gradle +++ b/build.gradle @@ -3,13 +3,9 @@ buildscript { repositories { jcenter() - maven { - url "http://nexus.arcsmed.at/content/repositories/public-snapshots/" - } } dependencies { classpath 'com.android.tools.build:gradle:2.2.3' - classpath 'net.linguica.gradle:maven-settings-plugin:0.7.0-SNAPSHOT' // Use official one when available } } @@ -39,5 +35,4 @@ ext { buildToolsVersion = "25.0.2" } - apply plugin: 'android-reporting' \ No newline at end of file diff --git a/nexus_push.gradle b/nexus_push.gradle index 99876e2..e2cd2c4 100644 --- a/nexus_push.gradle +++ b/nexus_push.gradle @@ -1,84 +1,89 @@ -apply plugin: 'net.linguica.maven-settings' -apply plugin: 'maven-publish' +apply plugin: 'maven' -publishing { - publications { - maven(MavenPublication) { - artifactId = POM_ARTIFACT_ID - - pom.withXml { - def root = asNode() - root.appendNode('name', POM_NAME) - root.appendNode('description', POM_DESCRIPTION) - root.appendNode('url', POM_URL) - - def scm = root.appendNode('scm') - scm.appendNode('url', POM_SCM_URL) - scm.appendNode('connection', POM_SCM_CONNECTION) - scm.appendNode('developerConnection', POM_SCM_DEV_CONNECTION) +def getRepositoryUsername() { + return hasProperty('nexusUsername') ? nexusUsername : "" +} - def license = root.appendNode('licenses').appendNode('license') - license.appendNode('name', POM_LICENCE_NAME) - license.appendNode('url', POM_LICENCE_URL) - license.appendNode('distribution', POM_LICENCE_DIST) +def getRepositoryPassword() { + return hasProperty('nexusPassword') ? nexusPassword : "" +} - def developers = root.appendNode('developers') - def developer = developers.appendNode('developer') - developer.appendNode('id', POM_DEVELOPER_ID) - developer.appendNode('name', POM_DEVELOPER_NAME) +def publishLocal() { + return hasProperty('local') +} - developer = developers.appendNode('developer') - developer.appendNode('id', POM_DEVELOPER2_ID) - developer.appendNode('name', POM_DEVELOPER2_NAME) - } +afterEvaluate { project -> + uploadArchives { + repositories { + mavenDeployer { + pom.artifactId = POM_ARTIFACT_ID - def folder = new File("$buildDir/outputs/aar/") + if(publishLocal()){ + def localMavenRepo = 'file://' + new File(System.getProperty('user.home'), '.m2/repository').absolutePath + repository(url: localMavenRepo) + } + else { + repository(url: "http://nexus.arcsmed.at/content/repositories/android/") { + authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) + } + } + + pom.project { + name POM_NAME + packaging POM_PACKAGING + description POM_DESCRIPTION + url POM_URL - if(!folder.exists()){ - println "Output folder not found, skipping publish" - return; - } + scm { + url POM_SCM_URL + connection POM_SCM_CONNECTION + developerConnection POM_SCM_DEV_CONNECTION + } - def files = new FileNameFinder().getFileNames(folder.absolutePath, "*-release.aar"); + licenses { + license { + name POM_LICENCE_NAME + url POM_LICENCE_URL + distribution POM_LICENCE_DIST + } + } - if(files.size() == 0){ - println "No AAR file found, skipping publish" - return; + developers { + developer { + id POM_DEVELOPER_ID + name POM_DEVELOPER_NAME + } + } + } } - - artifact androidSourcesJar - artifact androidJavadocsJar - artifact files[0] } } - repositories { - maven { - name "at.ac.ait.hbs.android" - url "http://nexus.arcsmed.at/content/repositories/android/" + task androidJavadocs(type: Javadoc) { + //source = android.sourceSets.main.allJava + options { + linksOffline "http://d.android.com/reference", "${android.sdkDirectory}/docs/reference" } + source = android.sourceSets.main.java.sourceFiles + //classpath += project.files(android.plugin.getRuntimeJarList().join(File.pathSeparator)) + classpath += project.files(project.android.getBootClasspath().join(File.pathSeparator)) } -} -task androidJavadocs(type: Javadoc) { - //source = android.sourceSets.main.allJava - options { - linksOffline "http://d.android.com/reference", "${android.sdkDirectory}/docs/reference" + task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { + classifier = 'javadoc' + //basename = artifact_id + from androidJavadocs.destinationDir } - source = android.sourceSets.main.java.sourceFiles - //classpath += project.files(android.plugin.getRuntimeJarList().join(File.pathSeparator)) - classpath += project.files(project.android.getBootClasspath().join(File.pathSeparator)) -} -task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { - classifier = 'javadoc' - //basename = artifact_id - from androidJavadocs.destinationDir -} + task androidSourcesJar(type: Jar) { + classifier = 'sources' + //basename = artifact_id + //from android.sourceSets.main.allSource + from android.sourceSets.main.java.sourceFiles + } -task androidSourcesJar(type: Jar) { - classifier = 'sources' - //basename = artifact_id - //from android.sourceSets.main.allSource - from android.sourceSets.main.java.sourceFiles + artifacts { + archives androidSourcesJar + archives androidJavadocsJar + } } \ No newline at end of file From ec78c0687d393a5251383b5125de15325094310a Mon Sep 17 00:00:00 2001 From: m-rm Date: Mon, 16 Jan 2017 15:06:12 +0100 Subject: [PATCH 18/23] Switching lat & lon in some methods, write location in City class --- .../client/okhttp/WeatherDefaultClient.java | 2 +- .../weather/lib/model/City.java | 2 +- .../lib/provider/IWeatherProvider.java | 2 +- .../forecastio/ForecastIOWeatherProvider.java | 2 +- .../OpenweathermapProvider.java | 4 +-- .../WeatherUndergroundProvider.java | 32 ++++++++++--------- .../yahooweather/YahooWeatherProvider.java | 4 +-- .../client/volley/WeatherClientDefault.java | 2 +- 8 files changed, 26 insertions(+), 24 deletions(-) diff --git a/OkHttpClient/src/main/java/com/survivingwithandroid/weather/lib/client/okhttp/WeatherDefaultClient.java b/OkHttpClient/src/main/java/com/survivingwithandroid/weather/lib/client/okhttp/WeatherDefaultClient.java index afc1060..077e872 100644 --- a/OkHttpClient/src/main/java/com/survivingwithandroid/weather/lib/client/okhttp/WeatherDefaultClient.java +++ b/OkHttpClient/src/main/java/com/survivingwithandroid/weather/lib/client/okhttp/WeatherDefaultClient.java @@ -140,7 +140,7 @@ public void run() { */ @Override public void searchCity(double lat, double lon, CityEventListener listener) throws ApiKeyRequiredException { - String url = provider.getQueryCityURLByCoord(lon, lat); + String url = provider.getQueryCityURLByCoord(lat, lon); _doSearchCity(url, listener); } diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/model/City.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/model/City.java index c4d0c31..2e4816e 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/model/City.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/model/City.java @@ -170,7 +170,7 @@ public CityBuilder region(String region) { return this; } - public CityBuilder geoCoord(double lon, double lat) { + public CityBuilder geoCoord(double lat, double lon) { this.lat = lat; this.lon = lon; return this; diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/IWeatherProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/IWeatherProvider.java index d5d661d..2fade5c 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/IWeatherProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/IWeatherProvider.java @@ -59,7 +59,7 @@ public interface IWeatherProvider { public String getQueryCityURLByLocation(Location location) throws ApiKeyRequiredException; - public String getQueryCityURLByCoord(double lon, double lat) throws ApiKeyRequiredException; + public String getQueryCityURLByCoord(double lat, double lon) throws ApiKeyRequiredException; public void setConfig(WeatherConfig config); diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/forecastio/ForecastIOWeatherProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/forecastio/ForecastIOWeatherProvider.java index d4f7e2d..1d96fdb 100644 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/forecastio/ForecastIOWeatherProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/forecastio/ForecastIOWeatherProvider.java @@ -124,7 +124,7 @@ public String getQueryCityURLByLocation(Location location) throws ApiKeyRequired } @Override - public String getQueryCityURLByCoord(double lon, double lat) throws ApiKeyRequiredException { + public String getQueryCityURLByCoord(double lat, double lon) throws ApiKeyRequiredException { return null; } diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/openweathermap/OpenweathermapProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/openweathermap/OpenweathermapProvider.java index 0e1e974..3036404 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/openweathermap/OpenweathermapProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/openweathermap/OpenweathermapProvider.java @@ -464,11 +464,11 @@ public void setWeatherCodeProvider(IWeatherCodeProvider codeProvider) { @Override public String getQueryCityURLByLocation(android.location.Location location) throws ApiKeyRequiredException { - return SEARCH_URL_GEO + "&lat=" + location.getLatitude() + "&lon=" + location.getLongitude() + "&cnt=3" + createAPPID(); + return getQueryCityURLByCoord(location.getLatitude(), location.getLongitude()); } @Override - public String getQueryCityURLByCoord(double lon, double lat) throws ApiKeyRequiredException { + public String getQueryCityURLByCoord(double lat, double lon) throws ApiKeyRequiredException { return SEARCH_URL_GEO + "&lat=" + lat + "&lon=" + lon + "&cnt=3" + createAPPID() ; } diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java index d96b026..e81c079 100644 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java @@ -254,24 +254,29 @@ private void parseForecast(JSONObject root, Weather weather) throws JSONExceptio public List getCityResultList(String data) throws WeatherLibException { - List cityList = new ArrayList(); + final List cityList = new ArrayList(); // Log.d("SwA", "Data ["+data+"]"); try { - JSONObject jObj = new JSONObject(data); - JSONArray jArr = jObj.getJSONArray("RESULTS"); + final JSONObject jObj = new JSONObject(data); + final JSONArray jArr = jObj.getJSONArray("RESULTS"); for (int i = 0; i < jArr.length(); i++) { - JSONObject obj = jArr.getJSONObject(i); + final JSONObject obj = jArr.getJSONObject(i); - String name = obj.getString("name"); - String id = obj.getString("l"); - String country = obj.getString("c"); + final String name = obj.getString("name"); + final String id = obj.getString("l"); + final String country = obj.getString("c"); + final double latitude = obj.getDouble("lat"); + final double longitude = obj.getDouble("lon"); //Log.d("SwA", "ID [" + id + "]"); - City.CityBuilder builder = new City.CityBuilder().name(name).id(id).country(country); - // City c = new City(id, name, null, country); - City c = builder.build(); + final City c = new City.CityBuilder() + .name(name) + .id(id) + .country(country) + .geoCoord(latitude, longitude) + .build(); cityList.add(c); } @@ -468,14 +473,11 @@ public void setWeatherCodeProvider(IWeatherCodeProvider codeProvider) { @Override public String getQueryCityURLByLocation(android.location.Location location) throws ApiKeyRequiredException { - if (config.ApiKey == null) - throw new ApiKeyRequiredException(); - - return BASE_URL_ID + "/" + config.ApiKey + "/geolookup/q/" + location.getLatitude() + "," + location.getLongitude() + ".json"; + return getQueryCityURLByCoord(location.getLatitude(), location.getLongitude()); } @Override - public String getQueryCityURLByCoord(double lon, double lat) throws ApiKeyRequiredException { + public String getQueryCityURLByCoord(double lat, double lon) throws ApiKeyRequiredException { if (config.ApiKey == null) throw new ApiKeyRequiredException(); diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java index d7931c4..bc70009 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java @@ -177,8 +177,8 @@ public String getQueryCityURLByLocation(Location location) throws ApiKeyRequired } @Override - public String getQueryCityURLByCoord(double lon, double lat) throws ApiKeyRequiredException { - return getQueryCityURLFromString(lon + ", " + lat); + public String getQueryCityURLByCoord(double lat, double lon) throws ApiKeyRequiredException { + return getQueryCityURLFromString(lat + ", " + lon); } @Override diff --git a/volleyclient/src/main/java/com/survivingwithandroid/weather/lib/client/volley/WeatherClientDefault.java b/volleyclient/src/main/java/com/survivingwithandroid/weather/lib/client/volley/WeatherClientDefault.java index b8a5fcb..6cea6fd 100644 --- a/volleyclient/src/main/java/com/survivingwithandroid/weather/lib/client/volley/WeatherClientDefault.java +++ b/volleyclient/src/main/java/com/survivingwithandroid/weather/lib/client/volley/WeatherClientDefault.java @@ -193,7 +193,7 @@ public void onErrorResponse(VolleyError volleyError) { */ @Override public void searchCity(double lat, double lon, CityEventListener listener) throws ApiKeyRequiredException { - String url = provider.getQueryCityURLByCoord(lon, lat); + String url = provider.getQueryCityURLByCoord(lat, lon); _doSearch(url, listener); } From a353a4f1d452f5c9b85a5f91fd44d1aa7c52146a Mon Sep 17 00:00:00 2001 From: m-rm Date: Mon, 16 Jan 2017 16:47:52 +0100 Subject: [PATCH 19/23] Refactor WeatherUndergroundProvider, add parsed humidity to forecast --- .../WeatherUndergroundProvider.java | 92 +++++++------------ .../weather/lib/request/WeatherRequest.java | 2 +- 2 files changed, 33 insertions(+), 61 deletions(-) diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java index e81c079..0d9b7f7 100644 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java @@ -61,17 +61,13 @@ public class WeatherUndergroundProvider implements IWeatherProvider { - private static String BASE_URL_ID = "http://api.wunderground.com/api"; private static String IMG_URL = "http://icons.wxug.com/i/c/k/"; private static String SEARCH_URL = "http://autocomplete.wunderground.com/aq?query="; - private static String BASE_FORECAST_URL_ID = "http://api.wunderground.com/api"; - private WeatherConfig config; private BaseWeather.WeatherUnit units = new BaseWeather.WeatherUnit(); private IWeatherCodeProvider codeProvider; - private WeatherForecast forecast = new WeatherForecast(); public CurrentWeather getCurrentCondition(String data) throws WeatherLibException { //Log.d("SwA", "JSON CurrentWeather [" + data + "]"); @@ -148,9 +144,9 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio weather.currentCondition.setHeatIndex(getString("heat_index_f", jObj)); } + // Forecast is parsed for today's min/max temp parseForecast(rootObj, weather); - // Astronomy JSONObject moonObj = getObject("moon_phase", rootObj); weather.location.getAstronomy().percIllum = getString("percentIlluminated", moonObj); @@ -191,19 +187,20 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio public WeatherForecast getForecastWeather(String data) throws WeatherLibException { try { JSONObject rootObj = new JSONObject(data); - parseForecast(rootObj, null); + return parseForecast(rootObj, null); } catch (JSONException json) { json.printStackTrace(); throw new WeatherLibException(json); } - return forecast; } - private void parseForecast(JSONObject root, Weather weather) throws JSONException { + private WeatherForecast parseForecast(JSONObject root, Weather weather) throws JSONException { // Start parsing forecast - JSONObject forecast1 = getObject("forecast", root); - JSONObject simpleForecast = getObject("simpleforecast", forecast1); - JSONArray jArr = simpleForecast.getJSONArray("forecastday"); + final JSONObject forecast1 = getObject("forecast", root); + final JSONObject simpleForecast = getObject("simpleforecast", forecast1); + final JSONArray jArr = simpleForecast.getJSONArray("forecastday"); + + WeatherForecast forecast = new WeatherForecast(); for (int i = 0; i < jArr.length(); i++) { JSONObject dayForecast = jArr.getJSONObject(i); @@ -213,6 +210,7 @@ private void parseForecast(JSONObject root, Weather weather) throws JSONExceptio df.weather.currentCondition.setDescr(dayForecast.getString("conditions")); df.weather.currentCondition.setIcon(dayForecast.getString("icon")); + df.weather.currentCondition.setHumidity(dayForecast.getInt("avehumidity")); if (codeProvider != null) { try { @@ -250,6 +248,7 @@ private void parseForecast(JSONObject root, Weather weather) throws JSONExceptio } forecast.setUnit(units); + return forecast; } @@ -531,74 +530,47 @@ private int getInt(String tagName, JSONObject jObj) throws JSONException { return jObj.getInt(tagName); } - private String addLanguage(String url) { - if (config.lang == null) - return url; + private String buildURL(final WeatherRequest request, final String type) throws ApiKeyRequiredException{ + if (config.ApiKey == null) { + throw new ApiKeyRequiredException(); + } - String nUrl = url + "/lang:" + config.lang.toUpperCase() + "/"; - return nUrl; - } + String location = request.getCityId(); + if (location == null) { + location = request.getLat() + "," + request.getLon(); + } + String language = "EN"; + if (config.lang != null) { + language = config.lang.toUpperCase(); + } + + final String url = String.format("%s/%s/%s/lang:%s/q/%s.json", BASE_URL_ID, config.ApiKey, type, language, location); + + return url; + } // New methods @Override public String getQueryCurrentWeatherURL(WeatherRequest request) throws ApiKeyRequiredException { - if (config.ApiKey == null) - throw new ApiKeyRequiredException(); - - String url = BASE_URL_ID + "/" + config.ApiKey + "/forecast/conditions/astronomy/"; - url = addLanguage(url); - if (request.getCityId() != null) - url = url + request.getCityId() + ".json"; - else - url = url + request.getLat() + "," + request.getLon() + ".json"; - return url; + return buildURL(request, "conditions/forecast/astronomy"); } @Override public String getQueryForecastWeatherURL(WeatherRequest request) throws ApiKeyRequiredException { - if (config.ApiKey == null) - throw new ApiKeyRequiredException(); - - String url = BASE_FORECAST_URL_ID + "/" + config.ApiKey + "/forecast/"; - url = addLanguage(url); - if (request.getCityId() != null) - url = url + request.getCityId() + ".json"; - else - url = url + request.getLat() + "," + request.getLon() + ".json"; - - return url; + return buildURL(request, "forecast"); } @Override public String getQueryHourForecastWeatherURL(WeatherRequest request) throws ApiKeyRequiredException { - if (config.ApiKey == null) - throw new ApiKeyRequiredException(); - - String url = BASE_FORECAST_URL_ID + "/" + config.ApiKey + "/hourly/"; - url = addLanguage(url); - if (request.getCityId() != null) - url = url + request.getCityId() + ".json"; - else - url = url + request.getLat() + "," + request.getLon() + ".json"; - - return url; + return buildURL(request, "hourly"); } @Override public String getQueryHistoricalWeatherURL(WeatherRequest request, Date startDate, Date endDate) throws ApiKeyRequiredException { - if (config.ApiKey == null) - throw new ApiKeyRequiredException(); + final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); - String url = BASE_URL_ID + "/" + config.ApiKey + "/history_" + sdf.format(startDate); - url = addLanguage(url); - if (request.getCityId() != null) - url = url + request.getCityId() + ".json"; - else - url = url + request.getLat() + "," + request.getLon() + ".json"; - - return url; + return buildURL(request, "history_" + sdf.format(startDate)); } } diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/request/WeatherRequest.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/request/WeatherRequest.java index 05da72f..f8ce341 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/request/WeatherRequest.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/request/WeatherRequest.java @@ -32,7 +32,7 @@ public WeatherRequest(String cityId) { this.cityId = cityId; } - public WeatherRequest(double lon, double lat) { + public WeatherRequest(double lat, double lon) { this.lon = lon; this.lat = lat; } From 632ab8ac18ee45f368dbb1b73ee73a74248fe509 Mon Sep 17 00:00:00 2001 From: m-rm Date: Thu, 19 Jan 2017 10:04:18 +0100 Subject: [PATCH 20/23] Adding Android Location to WeatherRequest possibilities --- .../weather/lib/request/WeatherRequest.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/request/WeatherRequest.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/request/WeatherRequest.java index f8ce341..38059f0 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/request/WeatherRequest.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/request/WeatherRequest.java @@ -16,13 +16,15 @@ */ package com.survivingwithandroid.weather.lib.request; +import android.location.Location; + /** * This class encapsulates the request parameters that must be passed to the weather client to get the weather condition. * The request can be made using cityId (a unique identifier) or using latitude and longitude * * @author Francesco Azzola * @since 1.5.1 - * */ + */ public class WeatherRequest { private String cityId; private double lon; @@ -32,9 +34,14 @@ public WeatherRequest(String cityId) { this.cityId = cityId; } + public WeatherRequest(Location location) { + this.lat = location.getLatitude(); + this.lon = location.getLongitude(); + } + public WeatherRequest(double lat, double lon) { - this.lon = lon; this.lat = lat; + this.lon = lon; } public String getCityId() { From 00cdaeb0daae42a72815c9cf9a642a269ec9faeb Mon Sep 17 00:00:00 2001 From: m-rm Date: Thu, 19 Jan 2017 17:46:43 +0100 Subject: [PATCH 21/23] Refactoring model and providers --- .../weatherapp/adapter/WeatherAdapter.java | 4 +- .../fragment/CurrentWeatherFragment.java | 6 +- .../weather/lib/DefaultValues.java | 21 + .../weather/lib/model/DayForecast.java | 14 +- .../weather/lib/model/Location.java | 38 +- .../weather/lib/model/Weather.java | 157 +++--- .../lib/model/WeatherForecastData.java | 4 +- .../forecastio/ForecastIOWeatherProvider.java | 26 +- .../OpenweathermapProvider.java | 64 +-- .../WeatherUndergroundProvider.java | 466 +++++++----------- .../yahooweather/YahooWeatherProvider.java | 60 ++- .../weather/lib/util/WeatherUtility.java | 50 +- 12 files changed, 442 insertions(+), 468 deletions(-) create mode 100644 lib/src/main/java/com/survivingwithandroid/weather/lib/DefaultValues.java diff --git a/demo/src/main/java/com/survivingwithandroid/weatherapp/adapter/WeatherAdapter.java b/demo/src/main/java/com/survivingwithandroid/weatherapp/adapter/WeatherAdapter.java index 727aea7..32d6b97 100644 --- a/demo/src/main/java/com/survivingwithandroid/weatherapp/adapter/WeatherAdapter.java +++ b/demo/src/main/java/com/survivingwithandroid/weatherapp/adapter/WeatherAdapter.java @@ -97,8 +97,8 @@ public View getView(int position, View convertView, ViewGroup parent) { dayCloud.setText("" + forecast.weather.clouds.getPerc() + "%"); dayDescr.setText(forecast.weather.currentCondition.getDescr()); try { - float rainVal = forecast.weather.rain[0].getAmmount(); - dayRain.setText("Rain:" + String.valueOf((int) rainVal)); + final Double rainVal = forecast.weather.rain[0].getAmmount(); + dayRain.setText("Rain:" + rainVal.intValue()); } catch(Throwable t) {} return convertView; diff --git a/demo/src/main/java/com/survivingwithandroid/weatherapp/fragment/CurrentWeatherFragment.java b/demo/src/main/java/com/survivingwithandroid/weatherapp/fragment/CurrentWeatherFragment.java index 87bf6f9..4804939 100644 --- a/demo/src/main/java/com/survivingwithandroid/weatherapp/fragment/CurrentWeatherFragment.java +++ b/demo/src/main/java/com/survivingwithandroid/weatherapp/fragment/CurrentWeatherFragment.java @@ -146,14 +146,14 @@ public void onWeatherRetrieved(CurrentWeather cWeather) { condDescr.setText(weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")"); LogUtils.LOGD("SwA", "Temp [" + temp + "]"); LogUtils.LOGD("SwA", "Val [" + weather.temperature.getTemp() + "]"); - temp.setText("" + ((int) weather.temperature.getTemp())); + temp.setText(weather.temperature.getTemp().intValue()); unitTemp.setText(cWeather.getUnit().tempUnit); - colorTextLine.setBackgroundResource(WeatherUtil.getResource(weather.temperature.getTemp(), config)); + colorTextLine.setBackgroundResource(WeatherUtil.getResource(weather.temperature.getTemp().floatValue(), config)); hum.setText(weather.currentCondition.getHumidity() + "%"); tempMin.setText(weather.temperature.getMinTemp() + cWeather.getUnit().tempUnit); tempMax.setText(weather.temperature.getMaxTemp() + cWeather.getUnit().tempUnit); windSpeed.setText(weather.wind.getSpeed() + cWeather.getUnit().speedUnit); - windDeg.setText((int) weather.wind.getDeg() + "° (" + WindDirection.getDir((int) weather.wind.getDeg()) + ")"); + windDeg.setText(weather.wind.getDeg().intValue() + "° (" + WindDirection.getDir(weather.wind.getDeg().intValue()) + ")"); press.setText(weather.currentCondition.getPressure() + cWeather.getUnit().pressureUnit); sunrise.setText(WeatherUtil.convertDate(weather.location.getSunrise())); diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/DefaultValues.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/DefaultValues.java new file mode 100644 index 0000000..93a0497 --- /dev/null +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/DefaultValues.java @@ -0,0 +1,21 @@ +package com.survivingwithandroid.weather.lib; + +/** + * Created by muellner-riederm on 19.01.2017. + */ + +public final class DefaultValues { + private DefaultValues() {} + + // These values are used if no value was assigned + public static Integer DEFAULT_INTEGER = null; + public static Long DEFAULT_LONG = null; + public static Double DEFAULT_DOUBLE = null; + public static String DEFAULT_STRING = ""; + + // These values are used when parsing fails + public static Integer ERROR_INTEGER = null; + public static Long ERROR_LONG = null; + public static Double ERROR_DOUBLE = null; + public static String ERROR_STRING = ""; +} diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/model/DayForecast.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/model/DayForecast.java index 76b5875..398a08d 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/model/DayForecast.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/model/DayForecast.java @@ -16,6 +16,8 @@ */ package com.survivingwithandroid.weather.lib.model; +import com.survivingwithandroid.weather.lib.DefaultValues; + import java.text.SimpleDateFormat; import java.util.Date; @@ -33,12 +35,12 @@ public class DayForecast extends WeatherForecastData { * Forecast temperature * */ public class ForecastTemp { - public float day; - public float min; - public float max; - public float night; - public float eve; - public float morning; + public Double day = DefaultValues.DEFAULT_DOUBLE; + public Double min = DefaultValues.DEFAULT_DOUBLE; + public Double max = DefaultValues.DEFAULT_DOUBLE; + public Double night = DefaultValues.DEFAULT_DOUBLE; + public Double eve = DefaultValues.DEFAULT_DOUBLE; + public Double morning = DefaultValues.DEFAULT_DOUBLE; } public String getStringDate() { diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/model/Location.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/model/Location.java index 110b0a5..7ff33f5 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/model/Location.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/model/Location.java @@ -16,6 +16,8 @@ */ package com.survivingwithandroid.weather.lib.model; +import com.survivingwithandroid.weather.lib.DefaultValues; + import java.io.Serializable; /** @@ -26,45 +28,45 @@ public class Location implements Serializable { - private float longitude; - private float latitude; - private long sunset; - private long sunrise; - private String country; - private String city; - private String region; + private Double longitude = DefaultValues.DEFAULT_DOUBLE; + private Double latitude = DefaultValues.DEFAULT_DOUBLE; + private Long sunset = DefaultValues.DEFAULT_LONG; + private Long sunrise = DefaultValues.DEFAULT_LONG; + private String country = DefaultValues.DEFAULT_STRING; + private String city = DefaultValues.DEFAULT_STRING; + private String region = DefaultValues.DEFAULT_STRING; private Astronomy astronomy = new Astronomy(); - private long population; + private Long population = DefaultValues.DEFAULT_LONG; - public float getLongitude() { + public Double getLongitude() { return longitude; } - public void setLongitude(float longitude) { + public void setLongitude(Double longitude) { this.longitude = longitude; } - public float getLatitude() { + public Double getLatitude() { return latitude; } - public void setLatitude(float latitude) { + public void setLatitude(Double latitude) { this.latitude = latitude; } - public long getSunset() { + public Long getSunset() { return sunset; } - public void setSunset(long sunset) { + public void setSunset(Long sunset) { this.sunset = sunset; } - public long getSunrise() { + public Long getSunrise() { return sunrise; } - public void setSunrise(long sunrise) { + public void setSunrise(Long sunrise) { this.sunrise = sunrise; } @@ -100,11 +102,11 @@ public void setAstronomy(Astronomy astronomy) { this.astronomy = astronomy; } - public long getPopulation() { + public Long getPopulation() { return population; } - public void setPopulation(long population) { + public void setPopulation(Long population) { this.population = population; } diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/model/Weather.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/model/Weather.java index 1e2f887..3a8da47 100644 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/model/Weather.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/model/Weather.java @@ -1,5 +1,6 @@ package com.survivingwithandroid.weather.lib.model; +import com.survivingwithandroid.weather.lib.DefaultValues; import com.survivingwithandroid.weather.lib.WeatherCode; /** @@ -30,28 +31,28 @@ public class Weather { * The values are represented using the {@link Weather.WeatherUnit} * */ public class Condition { - private int weatherId; - private String condition; - private String descr; - private String icon; - private float pressure; - private float humidity; - private float visibility; - private int pressureTrend; - private float feelsLike; - private float UV; - private float dewPoint; - private String heatIndex; - private String solarRadiation; - private float pressureSeaLevel; - private float pressureGroundLevel; + private Integer weatherId; + private String condition = DefaultValues.DEFAULT_STRING; + private String descr = DefaultValues.DEFAULT_STRING; + private String icon = DefaultValues.DEFAULT_STRING; + private Double pressure = DefaultValues.DEFAULT_DOUBLE; + private Double humidity = DefaultValues.DEFAULT_DOUBLE; + private Double visibility = DefaultValues.DEFAULT_DOUBLE; + private Integer pressureTrend = DefaultValues.DEFAULT_INTEGER; + private Double feelsLike = DefaultValues.DEFAULT_DOUBLE; + private Double UV = DefaultValues.DEFAULT_DOUBLE; + private Double dewPoint = DefaultValues.DEFAULT_DOUBLE; + private String heatIndex = DefaultValues.DEFAULT_STRING; + private String solarRadiation = DefaultValues.DEFAULT_STRING; + private Double pressureSeaLevel = DefaultValues.DEFAULT_DOUBLE; + private Double pressureGroundLevel = DefaultValues.DEFAULT_DOUBLE; private WeatherCode weatherCode; - public int getWeatherId() { + public Integer getWeatherId() { return weatherId; } - public void setWeatherId(int weatherId) { + public void setWeatherId(Integer weatherId) { this.weatherId = weatherId; } @@ -79,43 +80,43 @@ public void setIcon(String icon) { this.icon = icon; } - public float getPressure() { + public Double getPressure() { return pressure; } - public void setPressure(float pressure) { + public void setPressure(Double pressure) { this.pressure = pressure; } - public float getHumidity() { + public Double getHumidity() { return humidity; } - public void setHumidity(float humidity) { + public void setHumidity(Double humidity) { this.humidity = humidity; } - public float getFeelsLike() { + public Double getFeelsLike() { return feelsLike; } - public void setFeelsLike(float feelsLike) { + public void setFeelsLike(Double feelsLike) { this.feelsLike = feelsLike; } - public float getUV() { + public Double getUV() { return UV; } - public void setUV(float UV) { + public void setUV(Double UV) { this.UV = UV; } - public float getDewPoint() { + public Double getDewPoint() { return dewPoint; } - public void setDewPoint(float dewPoint) { + public void setDewPoint(Double dewPoint) { this.dewPoint = dewPoint; } @@ -135,19 +136,19 @@ public void setSolarRadiation(String solarRadiation) { this.solarRadiation = solarRadiation; } - public float getVisibility() { + public Double getVisibility() { return visibility; } - public void setVisibility(float visibility) { + public void setVisibility(Double visibility) { this.visibility = visibility; } - public int getPressureTrend() { + public Integer getPressureTrend() { return pressureTrend; } - public void setPressureTrend(int pressureTrend) { + public void setPressureTrend(Integer pressureTrend) { this.pressureTrend = pressureTrend; } @@ -159,19 +160,19 @@ public void setWeatherCode(WeatherCode weatherCode) { this.weatherCode = weatherCode; } - public float getPressureSeaLevel() { + public Double getPressureSeaLevel() { return pressureSeaLevel; } - public void setPressureSeaLevel(float pressureSeaLevel) { + public void setPressureSeaLevel(Double pressureSeaLevel) { this.pressureSeaLevel = pressureSeaLevel; } - public float getPressureGroundLevel() { + public Double getPressureGroundLevel() { return pressureGroundLevel; } - public void setPressureGroundLevel(float pressureGroundLevel) { + public void setPressureGroundLevel(Double pressureGroundLevel) { this.pressureGroundLevel = pressureGroundLevel; } } @@ -181,43 +182,43 @@ public void setPressureGroundLevel(float pressureGroundLevel) { * */ public class Temperature { - private float temp; - private float minTemp; - private float maxTemp; + private Double temp; + private Double minTemp; + private Double maxTemp; /* * Current temperature - * @return float + * @return Double * */ - public float getTemp() { + public Double getTemp() { return temp; } - public void setTemp(float temp) { + public void setTemp(Double temp) { this.temp = temp; } /* * Min temperature todat - * @return int + * @return Integer * */ - public float getMinTemp() { + public Double getMinTemp() { return minTemp; } - public void setMinTemp(float minTemp) { + public void setMinTemp(Double minTemp) { this.minTemp = minTemp; } /* * Max temperature today - * @return int + * @return Integer * */ - public float getMaxTemp() { + public Double getMaxTemp() { return maxTemp; } - public void setMaxTemp(float maxTemp) { + public void setMaxTemp(Double maxTemp) { this.maxTemp = maxTemp; } @@ -227,52 +228,52 @@ public void setMaxTemp(float maxTemp) { * Current Wind conditions * */ public class Wind { - private float speed; - private float deg; - private float chill; - private float gust; + private Double speed; + private Double deg; + private Double chill; + private Double gust; /* * Current wind speed - * @retrun float + * @retrun Double * */ - public float getSpeed() { + public Double getSpeed() { return speed; } - public void setSpeed(float speed) { + public void setSpeed(Double speed) { this.speed = speed; } /* * Current wind direction - * @retrun float + * @retrun Double * */ - public float getDeg() { + public Double getDeg() { return deg; } - public void setDeg(float deg) { + public void setDeg(Double deg) { this.deg = deg; } /* * Current wind chill - * @retrun float + * @retrun Double * */ - public float getChill() { + public Double getChill() { return chill; } - public void setChill(float chill) { + public void setChill(Double chill) { this.chill = chill; } - public float getGust() { + public Double getGust() { return gust; } - public void setGust(float gust) { + public void setGust(Double gust) { this.gust = gust; } } @@ -282,8 +283,8 @@ public void setGust(float gust) { * */ public class Rain { private String time; - private float ammount; - private float chance; + private Double ammount; + private Double chance; /** * Hour interval @@ -300,25 +301,25 @@ public void setTime(String time) { /** * Ammount of rain expected - * @return float + * @return Double * */ - public float getAmmount() { + public Double getAmmount() { return ammount; } - public void setAmmount(float ammount) { + public void setAmmount(Double ammount) { this.ammount = ammount; } /** * Chance of rain - * @return float + * @return Double * */ - public float getChance() { + public Double getChance() { return chance; } - public void setChance(float chance) { + public void setChance(Double chance) { this.chance = chance; } } @@ -328,7 +329,7 @@ public void setChance(float chance) { * */ public class Snow { private String time; - private float ammount; + private Double ammount; /* * Hour interval @@ -345,13 +346,13 @@ public void setTime(String time) { /* * Ammount of snouw expected - * @return float + * @return Double * */ - public float getAmmount() { + public Double getAmmount() { return ammount; } - public void setAmmount(float ammount) { + public void setAmmount(Double ammount) { this.ammount = ammount; } @@ -362,18 +363,18 @@ public void setAmmount(float ammount) { * Current cloud information * */ public class Clouds { - private int perc; + private Integer perc; /* * Coverage in % * - * @retrun int + * @retrun Integer */ - public int getPerc() { + public Integer getPerc() { return perc; } - public void setPerc(int perc) { + public void setPerc(Integer perc) { this.perc = perc; } diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/model/WeatherForecastData.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/model/WeatherForecastData.java index e164ccb..80a29a1 100644 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/model/WeatherForecastData.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/model/WeatherForecastData.java @@ -16,6 +16,8 @@ */ package com.survivingwithandroid.weather.lib.model; +import com.survivingwithandroid.weather.lib.DefaultValues; + /** * This is the basic class for weather forecast data. It holds some basic information * @@ -29,7 +31,7 @@ public class WeatherForecastData { /* * Forecast timestamp. Using this parameter you know at what day/hour the forecast information is refering to. * */ - public long timestamp; + public Long timestamp = DefaultValues.DEFAULT_LONG; } diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/forecastio/ForecastIOWeatherProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/forecastio/ForecastIOWeatherProvider.java index 1d96fdb..be81eb8 100644 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/forecastio/ForecastIOWeatherProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/forecastio/ForecastIOWeatherProvider.java @@ -176,8 +176,8 @@ private void parseData(String data) throws WeatherLibException { // Parse city com.survivingwithandroid.weather.lib.model.Location loc = new com.survivingwithandroid.weather.lib.model.Location(); - loc.setLatitude((float) rootObj.getDouble("latitude")); - loc.setLongitude((float) rootObj.getDouble("longitude")); + loc.setLatitude(rootObj.getDouble("latitude")); + loc.setLongitude(rootObj.getDouble("longitude")); weather.location = loc; @@ -245,22 +245,22 @@ private Weather parseWeather(JSONObject jsonWeather) throws JSONException { - weather.rain[0].setAmmount((float) jsonWeather.optDouble("precipIntensity")); + weather.rain[0].setAmmount(jsonWeather.optDouble("precipIntensity")); - weather.rain[0].setChance((float) jsonWeather.optDouble("precipProbability") * 100); + weather.rain[0].setChance(jsonWeather.optDouble("precipProbability") * 100); - weather.temperature.setTemp((float) jsonWeather.optDouble("temperature")); - weather.temperature.setMinTemp((float) jsonWeather.optDouble("temperatureMin")); - weather.temperature.setMaxTemp((float) jsonWeather.optDouble("temperatureMax")); - weather.currentCondition.setDewPoint((float) jsonWeather.optDouble("dewPoint")); + weather.temperature.setTemp(jsonWeather.optDouble("temperature")); + weather.temperature.setMinTemp(jsonWeather.optDouble("temperatureMin")); + weather.temperature.setMaxTemp(jsonWeather.optDouble("temperatureMax")); + weather.currentCondition.setDewPoint(jsonWeather.optDouble("dewPoint")); - weather.wind.setSpeed((float) jsonWeather.optDouble("windSpeed")); - weather.wind.setDeg((float) jsonWeather.optDouble("windBearing")); + weather.wind.setSpeed(jsonWeather.optDouble("windSpeed")); + weather.wind.setDeg(jsonWeather.optDouble("windBearing")); weather.clouds.setPerc((int) jsonWeather.optDouble("cloudCover") * 100); // We transform it in percentage - weather.currentCondition.setHumidity((float) jsonWeather.optDouble("humidity") * 100); - weather.currentCondition.setVisibility((float) jsonWeather.optDouble("visibility")); - weather.currentCondition.setPressure((float) jsonWeather.optDouble("pressure")); + weather.currentCondition.setHumidity(jsonWeather.optDouble("humidity") * 100); + weather.currentCondition.setVisibility(jsonWeather.optDouble("visibility")); + weather.currentCondition.setPressure(jsonWeather.optDouble("pressure")); return weather; } diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/openweathermap/OpenweathermapProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/openweathermap/OpenweathermapProvider.java index 3036404..6dc3899 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/openweathermap/OpenweathermapProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/openweathermap/OpenweathermapProvider.java @@ -94,8 +94,8 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio JSONObject sysObj = getObject("sys", jObj); loc.setCountry(getString("country", sysObj)); - loc.setSunrise(getInt("sunrise", sysObj)); - loc.setSunset(getInt("sunset", sysObj)); + loc.setSunrise(getLong("sunrise", sysObj)); + loc.setSunset(getLong("sunset", sysObj)); loc.setCity(getString("name", jObj)); weather.location = loc; @@ -121,10 +121,10 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio weather.currentCondition.setIcon(getString("icon", JSONWeather)); JSONObject mainObj = getObject("main", jObj); - weather.currentCondition.setHumidity(getInt("humidity", mainObj)); + weather.currentCondition.setHumidity(getFloat("humidity", mainObj)); weather.currentCondition.setPressure(getFloat("pressure", mainObj)); //#18 - weather.currentCondition.setPressureGroundLevel((float) mainObj.optDouble("grnd_level")); - weather.currentCondition.setPressureSeaLevel((float) mainObj.optDouble("sea_level")); + weather.currentCondition.setPressureGroundLevel(mainObj.optDouble("grnd_level")); + weather.currentCondition.setPressureSeaLevel(mainObj.optDouble("sea_level")); weather.temperature.setMaxTemp(getFloat("temp_max", mainObj)); weather.temperature.setMinTemp(getFloat("temp_min", mainObj)); weather.temperature.setTemp(getFloat("temp", mainObj)); @@ -140,7 +140,7 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio } */ - weather.wind.setGust((float) wObj.optDouble("gust")); + weather.wind.setGust(wObj.optDouble("gust")); // Clouds JSONObject cObj = getObject("clouds", jObj); weather.clouds.setPerc(getInt("all", cObj)); @@ -149,13 +149,13 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio JSONObject rObj = jObj.optJSONObject("rain"); if (rObj != null) { - float amm1 = (float) rObj.optDouble("1h"); + double amm1 = rObj.optDouble("1h"); if (amm1 > 0) { weather.rain[0].setAmmount(amm1); weather.rain[0].setTime("1h"); } - float amm3 = (float) rObj.optDouble("3h"); + double amm3 = rObj.optDouble("3h"); if (amm3 > 0) { weather.rain[1].setAmmount(amm3); weather.rain[1].setTime("3h"); @@ -165,7 +165,7 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio // Snow JSONObject sObj = jObj.optJSONObject("snow"); if (sObj != null) { - weather.snow.setAmmount((float) sObj.optDouble("3h")); + weather.snow.setAmmount(sObj.optDouble("3h")); weather.snow.setTime("3h"); } @@ -194,8 +194,8 @@ public WeatherForecast getForecastWeather(String data) throws WeatherLibExceptio JSONObject cObj = jObj.getJSONObject("city"); loc.setCity(cObj.getString("name")); JSONObject cooObj = cObj.getJSONObject("coord"); - loc.setLatitude((float) cooObj.getDouble("lat")); - loc.setLongitude((float) cooObj.getDouble("lon")); + loc.setLatitude(cooObj.getDouble("lat")); + loc.setLongitude(cooObj.getDouble("lon")); loc.setCountry(cObj.getString("country")); loc.setPopulation(cObj.getLong("population")); @@ -223,13 +223,13 @@ public WeatherForecast getForecastWeather(String data) throws WeatherLibExceptio JSONObject rObj = jObj.optJSONObject("rain"); if (rObj != null) { - float amm1 = (float) rObj.optDouble("1h"); + double amm1 = rObj.optDouble("1h"); if (amm1 > 0) { df.weather.rain[0].setAmmount(amm1); df.weather.rain[0].setTime("1h"); } - float amm3 = (float) rObj.optDouble("3h"); + double amm3 = rObj.optDouble("3h"); if (amm3 > 0) { df.weather.rain[1].setAmmount(amm3); df.weather.rain[1].setTime("3h"); @@ -238,16 +238,16 @@ public WeatherForecast getForecastWeather(String data) throws WeatherLibExceptio // Temp is an object JSONObject jTempObj = jDayForecast.getJSONObject("temp"); - df.forecastTemp.day = (float) jTempObj.getDouble("day"); - df.forecastTemp.min = (float) jTempObj.getDouble("min"); - df.forecastTemp.max = (float) jTempObj.getDouble("max"); - df.forecastTemp.night = (float) jTempObj.getDouble("night"); - df.forecastTemp.eve = (float) jTempObj.getDouble("eve"); - df.forecastTemp.morning = (float) jTempObj.getDouble("morn"); + df.forecastTemp.day = jTempObj.getDouble("day"); + df.forecastTemp.min = jTempObj.getDouble("min"); + df.forecastTemp.max = jTempObj.getDouble("max"); + df.forecastTemp.night = jTempObj.getDouble("night"); + df.forecastTemp.eve = jTempObj.getDouble("eve"); + df.forecastTemp.morning = jTempObj.getDouble("morn"); // Pressure & Humidity - df.weather.currentCondition.setPressure((float) jDayForecast.getDouble("pressure")); - df.weather.currentCondition.setHumidity((float) jDayForecast.getDouble("humidity")); + df.weather.currentCondition.setPressure(jDayForecast.getDouble("pressure")); + df.weather.currentCondition.setHumidity(jDayForecast.getDouble("humidity")); // ...and now the weather JSONArray jWeatherArr = jDayForecast.getJSONArray("weather"); @@ -327,8 +327,8 @@ public WeatherHourForecast getHourForecastWeather(String data) throws WeatherLib hourForecast.weather.temperature.setMinTemp(getFloat("temp_min", jMain)); hourForecast.weather.temperature.setMaxTemp(getFloat("temp_max", jMain)); hourForecast.weather.currentCondition.setPressure(getFloat("pressure", jMain)); - hourForecast.weather.currentCondition.setPressureSeaLevel((float) jMain.optDouble("sea_level")); - hourForecast.weather.currentCondition.setPressureGroundLevel((float) jMain.optDouble("grnd_level")); + hourForecast.weather.currentCondition.setPressureSeaLevel(jMain.optDouble("sea_level")); + hourForecast.weather.currentCondition.setPressureGroundLevel(jMain.optDouble("grnd_level")); hourForecast.weather.currentCondition.setHumidity(getFloat("humidity", jMain)); // Now the weather codes @@ -360,7 +360,7 @@ public WeatherHourForecast getHourForecastWeather(String data) throws WeatherLib JSONObject wObj = getObject("wind", jHour); hourForecast.weather.wind.setSpeed(getFloat("speed", wObj)); hourForecast.weather.wind.setDeg(getFloat("deg", wObj)); - hourForecast.weather.wind.setGust((float) wObj.optDouble("gust")); + hourForecast.weather.wind.setGust(wObj.optDouble("gust")); //Log.d("SwA", "Add weather forecast"); forecast.addForecast(hourForecast); @@ -392,11 +392,11 @@ public HistoricalWeather getHistoricalWeather(String data) throws WeatherLibExce JSONObject mainObj = getObject("main", jHour); - hhWeather.weather.currentCondition.setPressure((float) mainObj.getDouble("pressure")); + hhWeather.weather.currentCondition.setPressure(mainObj.getDouble("pressure")); - hhWeather.weather.temperature.setTemp((float) mainObj.getDouble("temp")); - hhWeather.weather.temperature.setMaxTemp((float) mainObj.getDouble("temp_max")); - hhWeather.weather.temperature.setMinTemp((float) mainObj.getDouble("temp_min")); + hhWeather.weather.temperature.setTemp(mainObj.getDouble("temp")); + hhWeather.weather.temperature.setMaxTemp(mainObj.getDouble("temp_max")); + hhWeather.weather.temperature.setMinTemp(mainObj.getDouble("temp_min")); JSONObject wObj = jHour.getJSONArray("weather").getJSONObject(0); hhWeather.weather.currentCondition.setDescr(wObj.getString("description")); @@ -415,8 +415,8 @@ public HistoricalWeather getHistoricalWeather(String data) throws WeatherLibExce } JSONObject windObj = getObject("wind", jHour); - hhWeather.weather.wind.setSpeed((float) windObj.getDouble("speed")); - hhWeather.weather.wind.setDeg((float) windObj.getDouble("deg")); + hhWeather.weather.wind.setSpeed(windObj.getDouble("speed")); + hhWeather.weather.wind.setDeg(windObj.getDouble("deg")); histWeather.addHistoricalHourWeather(hhWeather); } @@ -512,8 +512,8 @@ private static String getString(String tagName, JSONObject jObj) throws JSONExce return jObj.optString(tagName); } - private static float getFloat(String tagName, JSONObject jObj) throws JSONException { - return (float) jObj.optDouble(tagName); + private static Double getFloat(String tagName, JSONObject jObj) throws JSONException { + return jObj.optDouble(tagName); } private static int getInt(String tagName, JSONObject jObj) throws JSONException { diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java index 0d9b7f7..1182a65 100644 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java @@ -17,8 +17,6 @@ package com.survivingwithandroid.weather.lib.provider.wunderground; -import android.util.Log; - import com.survivingwithandroid.weather.lib.WeatherCode; import com.survivingwithandroid.weather.lib.WeatherConfig; import com.survivingwithandroid.weather.lib.exception.ApiKeyRequiredException; @@ -39,6 +37,7 @@ import com.survivingwithandroid.weather.lib.request.WeatherRequest; import com.survivingwithandroid.weather.lib.util.WeatherUtility; import com.survivingwithandroid.weather.lib.model.BaseWeather; + import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -70,31 +69,28 @@ public class WeatherUndergroundProvider implements IWeatherProvider { private IWeatherCodeProvider codeProvider; public CurrentWeather getCurrentCondition(String data) throws WeatherLibException { - //Log.d("SwA", "JSON CurrentWeather [" + data + "]"); - CurrentWeather cWeather = new CurrentWeather(); - Weather weather = new Weather(); try { + final CurrentWeather cWeather = new CurrentWeather(); + final Weather weather = new Weather(); + // We create out JSONObject from the data - JSONObject rootObj = new JSONObject(data); - JSONObject jObj = getObject("current_observation", rootObj); + final JSONObject rootObj = new JSONObject(data); + final JSONObject jObj = rootObj.getJSONObject("current_observation"); // We start extracting the info + final Location loc = new Location(); + final JSONObject dObj = jObj.getJSONObject("display_location"); - JSONObject dObj = getObject("display_location", jObj); - - Location loc = new Location(); - loc.setLatitude(getFloat("latitude", dObj)); - loc.setLongitude(getFloat("longitude", dObj)); - loc.setCountry(getString("state_name", dObj)); - loc.setCity(getString("city", dObj)); + loc.setLatitude(WeatherUtility.getDouble(dObj, "latitude")); + loc.setLongitude(WeatherUtility.getDouble(dObj, "longitude")); + loc.setCountry(WeatherUtility.getString(dObj, "state_name")); + loc.setCity(WeatherUtility.getString(dObj, "city")); weather.location = loc; - // Convert internal code - - weather.currentCondition.setDescr(getString("weather", jObj)); - //weather.currentCondition.setCondition(getString("main", JSONWeather)); - weather.currentCondition.setIcon(getString("icon", jObj)); + weather.currentCondition.setDescr(WeatherUtility.getString(jObj, "weather")); + weather.currentCondition.setIcon(WeatherUtility.getString(jObj, "icon")); + // Convert internal code if (codeProvider != null) { try { weather.currentCondition.setWeatherCode(codeProvider.getWeatherCode(weather.currentCondition.getIcon())); @@ -103,114 +99,118 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio weather.currentCondition.setWeatherCode(WeatherCode.NOT_AVAILABLE); } } - //JSONObject mainObj = getObject("main", jObj); - String relUm = getString("relative_humidity", jObj); - weather.currentCondition.setHumidity(Integer.parseInt(relUm.substring(0, relUm.length() - 1))); - weather.wind.setDeg(getFloat("wind_degrees", jObj)); - String trend = getString("pressure_trend", jObj); - - int trendVal = -1; - if ("-".equals(trend) || "+".equals(trend)) - trendVal = 0; - else - trendVal = Integer.parseInt(trend); - - weather.currentCondition.setPressureTrend(trendVal); - weather.currentCondition.setUV(getFloat("UV", jObj)); - weather.currentCondition.setSolarRadiation(getString("solarradiation", jObj)); + + final String relUm = WeatherUtility.getString(jObj, "relative_humidity"); + + if(relUm != null) { + try { + weather.currentCondition.setHumidity(Double.parseDouble(relUm.substring(0, relUm.length() - 1))); + } catch (NumberFormatException e) { + // + } + } + + weather.wind.setDeg(WeatherUtility.getDouble(jObj, "wind_degrees")); + + // At this point the pressure trend was set, but it was 0 all the time + // This is because wunderground can return 3 values: + - and 0, so mapping it to int makes no sense + + weather.currentCondition.setUV(WeatherUtility.getDouble(jObj, "UV")); + weather.currentCondition.setSolarRadiation(WeatherUtility.getString(jObj, "solarradiation")); if (WeatherUtility.isMetric(config.unitSystem)) { - weather.currentCondition.setPressure(getInt("pressure_mb", jObj)); - - weather.temperature.setTemp(getFloat("temp_c", jObj)); - // Wind - weather.wind.setGust(getFloat("wind_gust_kph", jObj)); - weather.wind.setSpeed(getFloat("wind_kph", jObj)); - weather.currentCondition.setVisibility(getFloat("visibility_km", jObj)); - weather.currentCondition.setFeelsLike(getFloat("feelslike_c", jObj)); - weather.currentCondition.setDewPoint(getFloat("dewpoint_c", jObj)); - weather.currentCondition.setHeatIndex(getString("heat_index_c", jObj)); + weather.currentCondition.setPressure(WeatherUtility.getDouble(jObj, "pressure_mb")); + weather.temperature.setTemp(WeatherUtility.getDouble(jObj, "temp_c")); + weather.wind.setGust(WeatherUtility.getDouble(jObj, "wind_gust_kph")); + weather.wind.setSpeed(WeatherUtility.getDouble(jObj, "wind_kph")); + weather.currentCondition.setVisibility(WeatherUtility.getDouble(jObj, "visibility_km")); + weather.currentCondition.setFeelsLike(WeatherUtility.getDouble(jObj, "feelslike_c")); + weather.currentCondition.setDewPoint(WeatherUtility.getDouble(jObj, "dewpoint_c")); + weather.currentCondition.setHeatIndex(WeatherUtility.getString(jObj, "heat_index_c")); } else { - weather.currentCondition.setPressure(getInt("pressure_in", jObj)); - // weather.temperature.setMaxTemp(getFloat("temp_max", mainObj)); - // weather.temperature.setMinTemp(getFloat("temp_min", mainObj)); - weather.temperature.setTemp(getFloat("temp_f", jObj)); - // Wind - weather.wind.setGust(getFloat("wind_gust_mph", jObj)); - weather.wind.setSpeed(getFloat("wind_mph", jObj)); - weather.currentCondition.setVisibility(getFloat("visibility_mi", jObj)); - weather.currentCondition.setFeelsLike(getFloat("feelslike_f", jObj)); - weather.currentCondition.setDewPoint(getFloat("dewpoint_f", jObj)); - weather.currentCondition.setHeatIndex(getString("heat_index_f", jObj)); + weather.currentCondition.setPressure(WeatherUtility.getDouble(jObj, "pressure_in")); + weather.temperature.setTemp(WeatherUtility.getDouble(jObj, "temp_f")); + weather.wind.setGust(WeatherUtility.getDouble(jObj, "wind_gust_mph")); + weather.wind.setSpeed(WeatherUtility.getDouble(jObj, "wind_mph")); + weather.currentCondition.setVisibility(WeatherUtility.getDouble(jObj, "visibility_mi")); + weather.currentCondition.setFeelsLike(WeatherUtility.getDouble(jObj, "feelslike_f")); + weather.currentCondition.setDewPoint(WeatherUtility.getDouble(jObj, "dewpoint_f")); + weather.currentCondition.setHeatIndex(WeatherUtility.getString(jObj, "heat_index_f")); } // Forecast is parsed for today's min/max temp parseForecast(rootObj, weather); // Astronomy - JSONObject moonObj = getObject("moon_phase", rootObj); - weather.location.getAstronomy().percIllum = getString("percentIlluminated", moonObj); - weather.location.getAstronomy().moonAge = getString("ageOfMoon", moonObj); - weather.location.getAstronomy().moonPhaseDescr = getString("phaseofMoon", moonObj); - weather.location.getAstronomy().hemisphere = getString("hemisphere", moonObj); - - SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); - JSONObject riseObj = getObject("sunrise", moonObj); - String d1 = getString("hour", riseObj) + ":" + getString("minute", riseObj); - try { - weather.location.setSunrise(sdf.parse(d1).getTime()); - } catch (ParseException e) { - //e.printStackTrace(); - } + if(rootObj.has("moon_phase")) { + final JSONObject moonObj = rootObj.getJSONObject("moon_phase"); + weather.location.getAstronomy().percIllum = WeatherUtility.getString(moonObj, "percentIlluminated"); + weather.location.getAstronomy().moonAge = WeatherUtility.getString(moonObj, "ageOfMoon"); + weather.location.getAstronomy().moonPhaseDescr = WeatherUtility.getString(moonObj, "phaseofMoon"); + weather.location.getAstronomy().hemisphere = WeatherUtility.getString(moonObj, "hemisphere"); + + final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); + + if(moonObj.has("sunrise")) { + final JSONObject riseObj = moonObj.getJSONObject("sunrise"); + final String d1 = WeatherUtility.getString(riseObj, "hour") + ":" + WeatherUtility.getString(riseObj, "minute"); + try { + weather.location.setSunrise(sdf.parse(d1).getTime()); + } catch (ParseException e) { + // + } + } - JSONObject setObj = getObject("sunset", moonObj); - String d2 = getString("hour", setObj) + ":" + getString("minute", setObj); - try { - weather.location.setSunset(sdf.parse(d2).getTime()); - } catch (ParseException e) { - // e.printStackTrace(); + if(moonObj.has("sunset")) { + final JSONObject setObj = moonObj.getJSONObject("sunset"); + final String d2 = WeatherUtility.getString(setObj, "hour") + ":" + WeatherUtility.getString(setObj, "minute"); + try { + weather.location.setSunset(sdf.parse(d2).getTime()); + } catch (ParseException e) { + // + } + } } + cWeather.setUnit(units); + cWeather.weather = weather; + return cWeather; } catch (JSONException json) { - //json.printStackTrace(); throw new WeatherLibException(json); } - - cWeather.setUnit(units); - cWeather.weather = weather; - - return cWeather; } - public WeatherForecast getForecastWeather(String data) throws WeatherLibException { try { - JSONObject rootObj = new JSONObject(data); + final JSONObject rootObj = new JSONObject(data); + return parseForecast(rootObj, null); } catch (JSONException json) { - json.printStackTrace(); throw new WeatherLibException(json); } } private WeatherForecast parseForecast(JSONObject root, Weather weather) throws JSONException { - // Start parsing forecast - final JSONObject forecast1 = getObject("forecast", root); - final JSONObject simpleForecast = getObject("simpleforecast", forecast1); + final JSONObject jsonForecast = root.getJSONObject("forecast"); + final JSONObject simpleForecast = jsonForecast.getJSONObject("simpleforecast"); final JSONArray jArr = simpleForecast.getJSONArray("forecastday"); - WeatherForecast forecast = new WeatherForecast(); + final WeatherForecast forecast = new WeatherForecast(); for (int i = 0; i < jArr.length(); i++) { - JSONObject dayForecast = jArr.getJSONObject(i); - DayForecast df = new DayForecast(); - JSONObject jsonDate = dayForecast.getJSONObject("date"); - df.timestamp = jsonDate.getLong("epoch"); + final DayForecast df = new DayForecast(); + + final JSONObject dayForecast = jArr.getJSONObject(i); - df.weather.currentCondition.setDescr(dayForecast.getString("conditions")); - df.weather.currentCondition.setIcon(dayForecast.getString("icon")); - df.weather.currentCondition.setHumidity(dayForecast.getInt("avehumidity")); + if(dayForecast.has("date")) { + final JSONObject jsonDate = dayForecast.getJSONObject("date"); + df.timestamp = WeatherUtility.getLong(jsonDate, "epoch"); + } + + df.weather.currentCondition.setDescr(WeatherUtility.getString(dayForecast, "conditions")); + df.weather.currentCondition.setIcon(WeatherUtility.getString(dayForecast, "icon")); + df.weather.currentCondition.setHumidity(WeatherUtility.getDouble(dayForecast, "avehumidity")); if (codeProvider != null) { try { @@ -221,24 +221,24 @@ private WeatherForecast parseForecast(JSONObject root, Weather weather) throws J } if (WeatherUtility.isMetric(config.unitSystem)) { - df.forecastTemp.max = dayForecast.getJSONObject("high").getInt("celsius"); - df.forecastTemp.min = dayForecast.getJSONObject("low").getInt("celsius"); - df.weather.wind.setSpeed(dayForecast.getJSONObject("avewind").getInt("kph")); + df.forecastTemp.max = WeatherUtility.getDouble(dayForecast, "high", "celsius"); + df.forecastTemp.min = WeatherUtility.getDouble(dayForecast, "low", "celsius"); + df.weather.wind.setSpeed(WeatherUtility.getDouble(dayForecast, "avewind", "kph")); df.weather.snow.setTime("Day"); - df.weather.snow.setAmmount(dayForecast.getJSONObject("snow_allday").getInt("cm")); + df.weather.snow.setAmmount(WeatherUtility.getDouble(dayForecast, "snow_allday", "cm")); df.weather.rain[0].setTime("Day"); - df.weather.rain[0].setAmmount(dayForecast.getJSONObject("qpf_allday").getInt("mm")); + df.weather.rain[0].setAmmount(WeatherUtility.getDouble(dayForecast, "qpf_allday", "mm")); } else { - df.forecastTemp.max = dayForecast.getJSONObject("high").getInt("fahrenheit"); - df.forecastTemp.min = dayForecast.getJSONObject("low").getInt("fahrenheit"); - df.weather.wind.setSpeed(dayForecast.getJSONObject("avewind").getInt("mph")); + df.forecastTemp.max = WeatherUtility.getDouble(dayForecast, "high", "fahrenheit"); + df.forecastTemp.min = WeatherUtility.getDouble(dayForecast, "low", "fahrenheit"); + df.weather.wind.setSpeed(WeatherUtility.getDouble(dayForecast, "avewind", "mph")); df.weather.snow.setTime("Day"); - df.weather.snow.setAmmount(dayForecast.getJSONObject("snow_allday").getInt("in")); + df.weather.snow.setAmmount(WeatherUtility.getDouble(dayForecast, "snow_allday", "in")); df.weather.rain[0].setTime("Day"); - df.weather.rain[0].setAmmount(dayForecast.getJSONObject("qpf_allday").getInt("in")); + df.weather.rain[0].setAmmount(WeatherUtility.getDouble(dayForecast, "qpf_allday", "in")); } - df.weather.wind.setDeg(dayForecast.getJSONObject("avewind").getInt("degrees")); + df.weather.wind.setDeg(WeatherUtility.getDouble(dayForecast, "avewind", "degrees")); if (i == 0 && weather != null) { weather.temperature.setMinTemp(df.forecastTemp.min); weather.temperature.setMaxTemp(df.forecastTemp.max); @@ -253,138 +253,117 @@ private WeatherForecast parseForecast(JSONObject root, Weather weather) throws J public List getCityResultList(String data) throws WeatherLibException { - final List cityList = new ArrayList(); - // Log.d("SwA", "Data ["+data+"]"); try { + final List cityList = new ArrayList(); final JSONObject jObj = new JSONObject(data); final JSONArray jArr = jObj.getJSONArray("RESULTS"); - for (int i = 0; i < jArr.length(); i++) { final JSONObject obj = jArr.getJSONObject(i); - final String name = obj.getString("name"); - final String id = obj.getString("l"); - final String country = obj.getString("c"); - final double latitude = obj.getDouble("lat"); - final double longitude = obj.getDouble("lon"); - //Log.d("SwA", "ID [" + id + "]"); final City c = new City.CityBuilder() - .name(name) - .id(id) - .country(country) - .geoCoord(latitude, longitude) + .name(obj.getString("name")) + .id(obj.getString("l")) + .country(obj.getString("c")) + .geoCoord(obj.getDouble("lat"), obj.getDouble("lon")) .build(); cityList.add(c); } + + return cityList; } catch (JSONException json) { throw new WeatherLibException(json); } - - return cityList; } @Override public WeatherHourForecast getHourForecastWeather(String data) throws WeatherLibException { - WeatherHourForecast forecast = new WeatherHourForecast(); try { - JSONObject jObj = new JSONObject(data); - JSONArray jHoursArray = jObj.getJSONArray("hourly_forecast"); + final WeatherHourForecast forecast = new WeatherHourForecast(); + + final JSONObject jObj = new JSONObject(data); + final JSONArray jHoursArray = jObj.getJSONArray("hourly_forecast"); + for (int i = 0; i < jHoursArray.length(); i++) { - JSONObject jHour = jHoursArray.getJSONObject(i); + final HourForecast hourForecast = new HourForecast(); - HourForecast hourForecast = new HourForecast(); - hourForecast.timestamp = jHour.getJSONObject("FCTTIME").getLong("epoch"); + final JSONObject jHour = jHoursArray.getJSONObject(i); + final String unitTag = WeatherUtility.isMetric(config.unitSystem) ? "metric" : "english"; - JSONObject jTemp = jHour.getJSONObject("temp"); - JSONObject jDewPoint = jHour.getJSONObject("dewpoint"); - JSONObject jWindSpeed = jHour.getJSONObject("wspd"); - JSONObject jWindDir = jHour.getJSONObject("wdir"); - JSONObject jHeatIdx = jHour.getJSONObject("heatindex"); - JSONObject jFeelslike = jHour.getJSONObject("feelslike"); - JSONObject jQPF = jHour.getJSONObject("qpf"); - JSONObject jSnow = jHour.getJSONObject("snow"); - - hourForecast.weather.currentCondition.setDescr(jHour.getString("conditions")); - hourForecast.weather.currentCondition.setIcon(jHour.getString("icon")); - hourForecast.weather.currentCondition.setHumidity(getFloat("humidity", jHour)); - hourForecast.weather.currentCondition.setUV(getFloat("uvi", jHour)); - hourForecast.weather.wind.setDeg(getFloat("degrees", jWindDir)); - - String tag = null; - if (WeatherUtility.isMetric(config.unitSystem)) - tag = "metric"; - else - tag = "english"; - - hourForecast.weather.temperature.setTemp(getFloat(tag, jTemp)); - hourForecast.weather.currentCondition.setDewPoint(getFloat(tag, jDewPoint)); - hourForecast.weather.wind.setSpeed(getFloat(tag, jWindSpeed)); - hourForecast.weather.currentCondition.setFeelsLike(getFloat(tag, jFeelslike)); - hourForecast.weather.currentCondition.setHeatIndex(getString(tag, jHeatIdx)); - hourForecast.weather.rain[0].setAmmount(getFloat(tag, jQPF)); - hourForecast.weather.snow.setAmmount(getFloat(tag, jSnow)); + hourForecast.timestamp = jHour.getJSONObject("FCTTIME").getLong("epoch"); + hourForecast.weather.currentCondition.setDescr(WeatherUtility.getString(jHour, "conditions")); + hourForecast.weather.currentCondition.setIcon(WeatherUtility.getString(jHour, "icon")); + hourForecast.weather.currentCondition.setHumidity(WeatherUtility.getDouble(jHour, "humidity")); + hourForecast.weather.currentCondition.setUV(WeatherUtility.getDouble(jHour, "uvi")); + hourForecast.weather.wind.setDeg(WeatherUtility.getDouble(jHour, "wdir", "degrees")); + hourForecast.weather.temperature.setTemp(WeatherUtility.getDouble(jHour, "temp", unitTag)); + hourForecast.weather.currentCondition.setDewPoint(WeatherUtility.getDouble(jHour, "dewpoint", unitTag)); + hourForecast.weather.wind.setSpeed(WeatherUtility.getDouble(jHour, "wspd", unitTag)); + hourForecast.weather.currentCondition.setFeelsLike(WeatherUtility.getDouble(jHour, "feelslike", unitTag)); + hourForecast.weather.currentCondition.setHeatIndex(WeatherUtility.getString(jHour, "heatindex", unitTag)); + hourForecast.weather.rain[0].setAmmount(WeatherUtility.getDouble(jHour, "qpf", unitTag)); + hourForecast.weather.snow.setAmmount(WeatherUtility.getDouble(jHour, "snow", unitTag)); forecast.addForecast(hourForecast); } + + return forecast; } catch (JSONException json) { throw new WeatherLibException(json); } - - return forecast; } @Override public HistoricalWeather getHistoricalWeather(String data) throws WeatherLibException { - HistoricalWeather histWeather = new HistoricalWeather(); try { - JSONObject jObj = new JSONObject(data); - JSONObject histObj = jObj.getJSONObject("history"); - // We move to the list tag - JSONArray wList = histObj.getJSONArray("observations"); - for (int i=0; i < wList.length(); i++) { - - HistoricalHourWeather hhWeather = new HistoricalHourWeather(); - - JSONObject jHour = wList.getJSONObject(i); - JSONObject utcObj = jHour.getJSONObject("utcdate"); - int y = utcObj.getInt("year"); - int m = utcObj.getInt("mon"); - int mday = utcObj.getInt("mday"); - int h = utcObj.getInt("hour"); - int min = utcObj.getInt("min"); - - Calendar cal = GregorianCalendar.getInstance(); - - cal.set(y,Calendar.JANUARY,mday,h,min); - cal.add(Calendar.MONTH, m - 1); - - hhWeather.timestamp = cal.getTimeInMillis(); - String tag = null; - if (WeatherUtility.isMetric(config.unitSystem)) - tag = "m"; - else - tag = "i"; - - hhWeather.weather.temperature.setTemp((float) jHour.getDouble("temp" + tag)); - hhWeather.weather.currentCondition.setDewPoint((float) jHour.getDouble("dewpt" + tag)); - hhWeather.weather.currentCondition.setHumidity((float) jHour.getInt("hum")); - hhWeather.weather.wind.setSpeed((float) jHour.getDouble("wspd" + tag)); - hhWeather.weather.wind.setGust((float) jHour.getDouble("wgust" + tag)); - hhWeather.weather.wind.setDeg((float) jHour.getDouble("wdird")); - hhWeather.weather.wind.setChill((float) jHour.getDouble("windchill" + tag)); - hhWeather.weather.currentCondition.setVisibility((float) jHour.getDouble("vis" + tag)); - hhWeather.weather.currentCondition.setPressure((float) jHour.getDouble("pressure" + tag)); - hhWeather.weather.currentCondition.setHeatIndex(jHour.getString("heatindex" + tag)); - hhWeather.weather.rain[0].setAmmount((float) jHour.getDouble("precip" + tag)); - hhWeather.weather.currentCondition.setDescr(jHour.getString("conds")); - hhWeather.weather.currentCondition.setIcon(jHour.getString("icon")); + final HistoricalWeather histWeather = new HistoricalWeather(); + + final JSONObject jObj = new JSONObject(data); + final JSONObject histObj = jObj.getJSONObject("history"); + final JSONArray wList = histObj.getJSONArray("observations"); + + for (int i = 0; i < wList.length(); i++) { + final HistoricalHourWeather hhWeather = new HistoricalHourWeather(); + final JSONObject jHour = wList.getJSONObject(i); + + try { + final JSONObject utcObj = jHour.getJSONObject("utcdate"); + final int y = utcObj.getInt("year"); + final int m = utcObj.getInt("mon"); + final int mday = utcObj.getInt("mday"); + final int h = utcObj.getInt("hour"); + final int min = utcObj.getInt("min"); + + final Calendar cal = GregorianCalendar.getInstance(); + cal.set(y, Calendar.JANUARY, mday, h, min); + cal.add(Calendar.MONTH, m - 1); + + hhWeather.timestamp = cal.getTimeInMillis(); + } catch (JSONException e) { + // + } + + final String tag = WeatherUtility.isMetric(config.unitSystem) ? "m" : "i"; + + hhWeather.weather.temperature.setTemp(WeatherUtility.getDouble(jHour, "temp" + tag)); + hhWeather.weather.currentCondition.setDewPoint(WeatherUtility.getDouble(jHour, "dewpt" + tag)); + hhWeather.weather.currentCondition.setHumidity(WeatherUtility.getDouble(jHour, "hum")); + hhWeather.weather.wind.setSpeed(WeatherUtility.getDouble(jHour, "wspd" + tag)); + hhWeather.weather.wind.setGust(WeatherUtility.getDouble(jHour, "wgust" + tag)); + hhWeather.weather.wind.setDeg(WeatherUtility.getDouble(jHour, "wdird")); + hhWeather.weather.wind.setChill(WeatherUtility.getDouble(jHour, "windchill" + tag)); + hhWeather.weather.currentCondition.setVisibility(WeatherUtility.getDouble(jHour, "vis" + tag)); + hhWeather.weather.currentCondition.setPressure(WeatherUtility.getDouble(jHour, "pressure" + tag)); + hhWeather.weather.currentCondition.setHeatIndex(WeatherUtility.getString(jHour, "heatindex" + tag)); + hhWeather.weather.rain[0].setAmmount(WeatherUtility.getDouble(jHour, "precip" + tag)); + hhWeather.weather.currentCondition.setDescr(WeatherUtility.getString(jHour, "conds")); + hhWeather.weather.currentCondition.setIcon(WeatherUtility.getString(jHour, "icon")); + if (codeProvider != null) { try { hhWeather.weather.currentCondition.setWeatherCode(codeProvider.getWeatherCode(hhWeather.weather.currentCondition.getIcon())); - } catch (Throwable t) { hhWeather.weather.currentCondition.setWeatherCode(WeatherCode.NOT_AVAILABLE); } @@ -392,18 +371,14 @@ public HistoricalWeather getHistoricalWeather(String data) throws WeatherLibExce // fog, hail, tornado and so on still not supported histWeather.addHistoricalHourWeather(hhWeather); - } - } - catch(JSONException json) { - throw new WeatherLibException(json); - } - + histWeather.setUnit(units); - histWeather.setUnit(units); - - return histWeather; + return histWeather; + } catch (JSONException json) { + throw new WeatherLibException(json); + } } @Override @@ -422,49 +397,11 @@ public String getQueryCityURL(String cityNamePattern) { return SEARCH_URL + cityNamePattern; // + "&cnt=" + config.maxResult; } - /* - @Override - public String getQueryCurrentWeatherURL(String cityId) { - if (config.ApiKey == null) - throw new ApiKeyRequiredException(); - - String url = BASE_URL_ID + "/" + config.ApiKey + "/forecast/conditions/astronomy/"; - url = addLanguage(url); - url = url + cityId + ".json"; - return url; - - } -*/ - /* - @Override - public String getQueryForecastWeatherURL(String cityId) { - if (config.ApiKey == null) - throw new ApiKeyRequiredException(); - - String url = BASE_FORECAST_URL_ID + "/" + config.ApiKey + "/forecast/"; - url = addLanguage(url); - return url + cityId + ".json"; - } -*/ - @Override public String getQueryImageURL(String icon) throws ApiKeyRequiredException { return IMG_URL + icon + ".gif"; } - /* - @Override - public String getQueryHourForecastWeatherURL(String cityId) throws ApiKeyRequiredException { - if (config.ApiKey == null) - throw new ApiKeyRequiredException(); - - String url = BASE_FORECAST_URL_ID + "/" + config.ApiKey + "/hourly/"; - url = addLanguage(url); - return url + cityId + ".json"; - - } - */ - @Override public void setWeatherCodeProvider(IWeatherCodeProvider codeProvider) { this.codeProvider = codeProvider; @@ -483,20 +420,6 @@ public String getQueryCityURLByCoord(double lat, double lon) throws ApiKeyRequir return BASE_URL_ID + "/" + config.ApiKey + "/geolookup/q/" + lat + "," + lon + ".json"; } - /* - @Override - public String getQueryHistoricalWeatherURL(String cityId, Date startDate, Date endDate) throws ApiKeyRequiredException { - if (config.ApiKey == null) - throw new ApiKeyRequiredException(); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); - String url = BASE_URL_ID + "/" + config.ApiKey + "/history_" + sdf.format(startDate); - url = addLanguage(url); - return url + cityId + ".json"; - - } - */ - @Override public String getQueryLayerURL(String cityId, Params params) throws ApiKeyRequiredException { if (config.ApiKey == null) @@ -509,27 +432,6 @@ public String getQueryLayerURL(String cityId, Params params) throws ApiKeyRequir return url; } - private JSONObject getObject(String tagName, JSONObject jObj) throws JSONException { - JSONObject subObj = jObj.getJSONObject(tagName); - return subObj; - } - - private String getString(String tagName, JSONObject jObj) throws JSONException { - return jObj.getString(tagName); - } - - private float getFloat(String tagName, JSONObject jObj) throws JSONException { - try { - return (float) jObj.getDouble(tagName); - } catch (Throwable t) { - return -1; - } - } - - private int getInt(String tagName, JSONObject jObj) throws JSONException { - return jObj.getInt(tagName); - } - private String buildURL(final WeatherRequest request, final String type) throws ApiKeyRequiredException{ if (config.ApiKey == null) { throw new ApiKeyRequiredException(); diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java index bc70009..714f64e 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/yahooweather/YahooWeatherProvider.java @@ -215,27 +215,27 @@ private Pair getWeather(final String data) thro if (event == XmlPullParser.START_TAG) { if (tagName.equals("yweather:wind")) { - current.wind.setChill(WeatherUtility.parseInt(parser.getAttributeValue(null, "chill"))); - current.wind.setDeg(WeatherUtility.parseInt(parser.getAttributeValue(null, "direction"))); - current.wind.setSpeed(WeatherUtility.parseFloat(parser.getAttributeValue(null, "speed"))); + current.wind.setChill(parseFloat(parser.getAttributeValue(null, "chill"))); + current.wind.setDeg(parseFloat(parser.getAttributeValue(null, "direction"))); + current.wind.setSpeed(parseFloat(parser.getAttributeValue(null, "speed"))); } else if (tagName.equals("yweather:atmosphere")) { - current.currentCondition.setHumidity(WeatherUtility.parseInt(parser.getAttributeValue(null, "humidity"))); - current.currentCondition.setVisibility(WeatherUtility.parseFloat(parser.getAttributeValue(null, "visibility"))); - current.currentCondition.setPressure(WeatherUtility.parseFloat(parser.getAttributeValue(null, "pressure"))); - current.currentCondition.setPressureTrend(WeatherUtility.parseInt(parser.getAttributeValue(null, "rising"))); + current.currentCondition.setHumidity(parseFloat(parser.getAttributeValue(null, "humidity"))); + current.currentCondition.setVisibility(parseFloat(parser.getAttributeValue(null, "visibility"))); + current.currentCondition.setPressure(parseFloat(parser.getAttributeValue(null, "pressure"))); + current.currentCondition.setPressureTrend(parseInt(parser.getAttributeValue(null, "rising"))); } else if (tagName.equals("yweather:forecast")) { if(isFirstDayForecast) { - current.temperature.setMinTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "low"))); - current.temperature.setMaxTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "high"))); + current.temperature.setMinTemp(parseFloat(parser.getAttributeValue(null, "low"))); + current.temperature.setMaxTemp(parseFloat(parser.getAttributeValue(null, "high"))); isFirstDayForecast = false; } DayForecast df = new DayForecast(); - df.forecastTemp.max = WeatherUtility.parseInt(parser.getAttributeValue(null, "high")); - df.forecastTemp.min = WeatherUtility.parseInt(parser.getAttributeValue(null, "low")); // Bug fixing - df.weather.currentCondition.setWeatherId(WeatherUtility.parseInt(parser.getAttributeValue(null, "code"))); + df.forecastTemp.max = parseFloat(parser.getAttributeValue(null, "high")); + df.forecastTemp.min = parseFloat(parser.getAttributeValue(null, "low")); // Bug fixing + df.weather.currentCondition.setWeatherId(parseInt(parser.getAttributeValue(null, "code"))); df.weather.location = current.location; if (codeProvider != null) { try { @@ -251,7 +251,7 @@ private Pair getWeather(final String data) thro forecast.addForecast(df); } else if (tagName.equals("yweather:condition")) { - current.currentCondition.setWeatherId(WeatherUtility.parseInt(parser.getAttributeValue(null, "code"))); + current.currentCondition.setWeatherId(parseInt(parser.getAttributeValue(null, "code"))); current.currentCondition.setIcon("" + current.currentCondition.getWeatherId()); // Convert the code @@ -265,7 +265,7 @@ private Pair getWeather(final String data) thro } current.currentCondition.setCondition(parser.getAttributeValue(null, "text")); - current.temperature.setTemp(WeatherUtility.parseInt(parser.getAttributeValue(null, "temp"))); + current.temperature.setTemp(parseFloat(parser.getAttributeValue(null, "temp"))); } else if (tagName.equals("yweather:location")) { current.location.setCity(parser.getAttributeValue(null, "city")); @@ -297,9 +297,9 @@ else if (event == XmlPullParser.TEXT) { } else if (event == XmlPullParser.END_TAG) { if (tagName.equals("geo:lat")){ - current.location.setLatitude(WeatherUtility.parseFloat(text)); + current.location.setLatitude(parseFloat(text)); } else if (tagName.equals("geo:long")){ - current.location.setLongitude(WeatherUtility.parseFloat(text)); + current.location.setLongitude(parseFloat(text)); } } @@ -387,4 +387,32 @@ public String getQueryHourForecastWeatherURL(WeatherRequest request) throws ApiK public String getQueryHistoricalWeatherURL(WeatherRequest request, Date startDate, Date endDate) throws ApiKeyRequiredException { throw new UnsupportedOperationException(); } + + // Place these temporary here since Yahoo is the only provider using it + + private static Integer parseInt(final String value){ + return parseInt(value, null); + } + + private static Integer parseInt(final String value, final Integer defaultValue){ + try{ + return Integer.parseInt(value); + } + catch (NumberFormatException e){ + return defaultValue; + } + } + + private static Double parseFloat(final String value){ + return parseFloat(value, null); + } + + private static Double parseFloat(final String value, final Double defaultValue){ + try { + return Double.parseDouble(value); + } + catch(Exception e){ + return defaultValue; + } + } } diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/util/WeatherUtility.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/util/WeatherUtility.java index 6cc4efa..4b1ef97 100755 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/util/WeatherUtility.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/util/WeatherUtility.java @@ -17,9 +17,13 @@ package com.survivingwithandroid.weather.lib.util; +import com.survivingwithandroid.weather.lib.DefaultValues; import com.survivingwithandroid.weather.lib.WeatherConfig; import com.survivingwithandroid.weather.lib.model.BaseWeather; +import org.json.JSONException; +import org.json.JSONObject; + public class WeatherUtility { public static BaseWeather.WeatherUnit createWeatherUnit(WeatherConfig.UNIT_SYSTEM unit) { @@ -45,37 +49,49 @@ public static boolean isMetric(WeatherConfig.UNIT_SYSTEM currentUnit) { return currentUnit.equals(WeatherConfig.UNIT_SYSTEM.M); } + private static JSONObject getLast(final JSONObject json, final String... names) throws JSONException { + final int lastIndex = names.length - 1; + JSONObject last = json; - public static float string2Float(String value) { - if (value == null || "".equals(value)) - return -1; + for (int i = 0; i < lastIndex; i++) { + last = last.getJSONObject(names[i]); + } - return Float.parseFloat(value); + return last; } - public static int parseInt(final String value){ - return parseInt(value, 0); + public static String getString(final JSONObject json, final String... names) { + try { + return getLast(json, names).getString(names[names.length - 1]); + } catch (JSONException e) { + return DefaultValues.ERROR_STRING; + } } - public static int parseInt(final String value, final int defaultValue){ + public static Integer getInteger(final JSONObject json, final String... names){ try{ - return Integer.parseInt(value); + return getLast(json, names).getInt(names[names.length - 1]); } - catch (NumberFormatException e){ - return defaultValue; + catch (JSONException e){ + return DefaultValues.ERROR_INTEGER; } } - public static float parseFloat(final String value){ - return parseFloat(value, -1.0f); + public static Long getLong(final JSONObject json, final String... names){ + try{ + return getLast(json, names).getLong(names[names.length - 1]); + } + catch (JSONException e){ + return DefaultValues.ERROR_LONG; + } } - public static float parseFloat(final String value, final float defaultValue){ - try { - return Float.parseFloat(value); + public static Double getDouble(final JSONObject json, final String... names){ + try{ + return getLast(json, names).getDouble(names[names.length - 1]); } - catch(Exception e){ - return defaultValue; + catch (JSONException e){ + return DefaultValues.ERROR_DOUBLE; } } } From 59edbe8f02f2c8058062fcf21eae6a656d71ef89 Mon Sep 17 00:00:00 2001 From: M-RM Date: Fri, 20 Jan 2017 09:54:55 +0100 Subject: [PATCH 22/23] Add snapshot repo --- gradle.properties | 2 +- nexus_push.gradle | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/gradle.properties b/gradle.properties index 83ea41e..90e5ea0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,4 +1,4 @@ -VERSION_NAME=1.6.1 +VERSION_NAME=1.6.1-SNAPSHOT VERSION_CODE=19 GROUP=at.ac.ait.hbs.android diff --git a/nexus_push.gradle b/nexus_push.gradle index e2cd2c4..349944c 100644 --- a/nexus_push.gradle +++ b/nexus_push.gradle @@ -23,9 +23,16 @@ afterEvaluate { project -> repository(url: localMavenRepo) } else { - repository(url: "http://nexus.arcsmed.at/content/repositories/android/") { - authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) - } + if(VERSION_NAME.endsWith('-SNAPSHOT')) { + repository(url: "http://nexus.arcsmed.at/content/repositories/android-snapshots/") { + authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) + } + } + else { + repository(url: "http://nexus.arcsmed.at/content/repositories/android/") { + authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) + } + } } pom.project { From ee7a4e2dcd683199777a5d8d1968b0513ac5ebbc Mon Sep 17 00:00:00 2001 From: M-RM Date: Fri, 20 Jan 2017 15:33:05 +0100 Subject: [PATCH 23/23] Refactoring provider --- .../WeatherUndergroundProvider.java | 126 ++++++++++-------- 1 file changed, 68 insertions(+), 58 deletions(-) diff --git a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java index 1182a65..1578b14 100644 --- a/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java +++ b/lib/src/main/java/com/survivingwithandroid/weather/lib/provider/wunderground/WeatherUndergroundProvider.java @@ -49,7 +49,7 @@ import java.util.Date; import java.util.GregorianCalendar; import java.util.List; - +import java.util.Locale; /** @@ -65,22 +65,24 @@ public class WeatherUndergroundProvider implements IWeatherProvider { private static String SEARCH_URL = "http://autocomplete.wunderground.com/aq?query="; private WeatherConfig config; - private BaseWeather.WeatherUnit units = new BaseWeather.WeatherUnit(); + private BaseWeather.WeatherUnit units; + private Units unitStrings; private IWeatherCodeProvider codeProvider; public CurrentWeather getCurrentCondition(String data) throws WeatherLibException { try { - final CurrentWeather cWeather = new CurrentWeather(); + final CurrentWeather currentWeather = new CurrentWeather(); + currentWeather.setUnit(units); + final Weather weather = new Weather(); + currentWeather.weather = weather; - // We create out JSONObject from the data final JSONObject rootObj = new JSONObject(data); final JSONObject jObj = rootObj.getJSONObject("current_observation"); - - // We start extracting the info - final Location loc = new Location(); final JSONObject dObj = jObj.getJSONObject("display_location"); + // Location + final Location loc = new Location(); loc.setLatitude(WeatherUtility.getDouble(dObj, "latitude")); loc.setLongitude(WeatherUtility.getDouble(dObj, "longitude")); loc.setCountry(WeatherUtility.getString(dObj, "state_name")); @@ -90,7 +92,7 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio weather.currentCondition.setDescr(WeatherUtility.getString(jObj, "weather")); weather.currentCondition.setIcon(WeatherUtility.getString(jObj, "icon")); - // Convert internal code + // WeatherCode: Convert to internal code if (codeProvider != null) { try { weather.currentCondition.setWeatherCode(codeProvider.getWeatherCode(weather.currentCondition.getIcon())); @@ -100,8 +102,8 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio } } + // Humidity final String relUm = WeatherUtility.getString(jObj, "relative_humidity"); - if(relUm != null) { try { weather.currentCondition.setHumidity(Double.parseDouble(relUm.substring(0, relUm.length() - 1))); @@ -110,33 +112,21 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio } } - weather.wind.setDeg(WeatherUtility.getDouble(jObj, "wind_degrees")); - // At this point the pressure trend was set, but it was 0 all the time // This is because wunderground can return 3 values: + - and 0, so mapping it to int makes no sense weather.currentCondition.setUV(WeatherUtility.getDouble(jObj, "UV")); weather.currentCondition.setSolarRadiation(WeatherUtility.getString(jObj, "solarradiation")); + weather.currentCondition.setPressure(WeatherUtility.getDouble(jObj, "pressure_" + unitStrings.pressure)); + weather.temperature.setTemp(WeatherUtility.getDouble(jObj, "temp_" + unitStrings.temperatureShort)); + weather.wind.setGust(WeatherUtility.getDouble(jObj, "wind_gust_" + unitStrings.speed)); + weather.wind.setSpeed(WeatherUtility.getDouble(jObj, "wind_" + unitStrings.speed)); + weather.wind.setDeg(WeatherUtility.getDouble(jObj, "wind_degrees")); + weather.currentCondition.setVisibility(WeatherUtility.getDouble(jObj, "visibility_" + unitStrings.distance)); + weather.currentCondition.setFeelsLike(WeatherUtility.getDouble(jObj, "feelslike_" + unitStrings.temperatureShort)); + weather.currentCondition.setDewPoint(WeatherUtility.getDouble(jObj, "dewpoint_" + unitStrings.temperatureShort)); + weather.currentCondition.setHeatIndex(WeatherUtility.getString(jObj, "heat_index_" + unitStrings.temperatureShort)); - if (WeatherUtility.isMetric(config.unitSystem)) { - weather.currentCondition.setPressure(WeatherUtility.getDouble(jObj, "pressure_mb")); - weather.temperature.setTemp(WeatherUtility.getDouble(jObj, "temp_c")); - weather.wind.setGust(WeatherUtility.getDouble(jObj, "wind_gust_kph")); - weather.wind.setSpeed(WeatherUtility.getDouble(jObj, "wind_kph")); - weather.currentCondition.setVisibility(WeatherUtility.getDouble(jObj, "visibility_km")); - weather.currentCondition.setFeelsLike(WeatherUtility.getDouble(jObj, "feelslike_c")); - weather.currentCondition.setDewPoint(WeatherUtility.getDouble(jObj, "dewpoint_c")); - weather.currentCondition.setHeatIndex(WeatherUtility.getString(jObj, "heat_index_c")); - } else { - weather.currentCondition.setPressure(WeatherUtility.getDouble(jObj, "pressure_in")); - weather.temperature.setTemp(WeatherUtility.getDouble(jObj, "temp_f")); - weather.wind.setGust(WeatherUtility.getDouble(jObj, "wind_gust_mph")); - weather.wind.setSpeed(WeatherUtility.getDouble(jObj, "wind_mph")); - weather.currentCondition.setVisibility(WeatherUtility.getDouble(jObj, "visibility_mi")); - weather.currentCondition.setFeelsLike(WeatherUtility.getDouble(jObj, "feelslike_f")); - weather.currentCondition.setDewPoint(WeatherUtility.getDouble(jObj, "dewpoint_f")); - weather.currentCondition.setHeatIndex(WeatherUtility.getString(jObj, "heat_index_f")); - } // Forecast is parsed for today's min/max temp parseForecast(rootObj, weather); @@ -149,7 +139,7 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio weather.location.getAstronomy().moonPhaseDescr = WeatherUtility.getString(moonObj, "phaseofMoon"); weather.location.getAstronomy().hemisphere = WeatherUtility.getString(moonObj, "hemisphere"); - final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); + final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.ENGLISH); if(moonObj.has("sunrise")) { final JSONObject riseObj = moonObj.getJSONObject("sunrise"); @@ -172,10 +162,7 @@ public CurrentWeather getCurrentCondition(String data) throws WeatherLibExceptio } } - cWeather.setUnit(units); - cWeather.weather = weather; - - return cWeather; + return currentWeather; } catch (JSONException json) { throw new WeatherLibException(json); } @@ -197,6 +184,7 @@ private WeatherForecast parseForecast(JSONObject root, Weather weather) throws J final JSONArray jArr = simpleForecast.getJSONArray("forecastday"); final WeatherForecast forecast = new WeatherForecast(); + forecast.setUnit(units); for (int i = 0; i < jArr.length(); i++) { final DayForecast df = new DayForecast(); @@ -220,25 +208,15 @@ private WeatherForecast parseForecast(JSONObject root, Weather weather) throws J } } - if (WeatherUtility.isMetric(config.unitSystem)) { - df.forecastTemp.max = WeatherUtility.getDouble(dayForecast, "high", "celsius"); - df.forecastTemp.min = WeatherUtility.getDouble(dayForecast, "low", "celsius"); - df.weather.wind.setSpeed(WeatherUtility.getDouble(dayForecast, "avewind", "kph")); - df.weather.snow.setTime("Day"); - df.weather.snow.setAmmount(WeatherUtility.getDouble(dayForecast, "snow_allday", "cm")); - df.weather.rain[0].setTime("Day"); - df.weather.rain[0].setAmmount(WeatherUtility.getDouble(dayForecast, "qpf_allday", "mm")); - } else { - df.forecastTemp.max = WeatherUtility.getDouble(dayForecast, "high", "fahrenheit"); - df.forecastTemp.min = WeatherUtility.getDouble(dayForecast, "low", "fahrenheit"); - df.weather.wind.setSpeed(WeatherUtility.getDouble(dayForecast, "avewind", "mph")); - df.weather.snow.setTime("Day"); - df.weather.snow.setAmmount(WeatherUtility.getDouble(dayForecast, "snow_allday", "in")); - df.weather.rain[0].setTime("Day"); - df.weather.rain[0].setAmmount(WeatherUtility.getDouble(dayForecast, "qpf_allday", "in")); - } - + df.forecastTemp.max = WeatherUtility.getDouble(dayForecast, "high", unitStrings.temperature); + df.forecastTemp.min = WeatherUtility.getDouble(dayForecast, "low", unitStrings.temperature); + df.weather.wind.setSpeed(WeatherUtility.getDouble(dayForecast, "avewind", unitStrings.speed)); df.weather.wind.setDeg(WeatherUtility.getDouble(dayForecast, "avewind", "degrees")); + df.weather.snow.setTime("Day"); + df.weather.snow.setAmmount(WeatherUtility.getDouble(dayForecast, "snow_allday", unitStrings.snowHeight)); + df.weather.rain[0].setTime("Day"); + df.weather.rain[0].setAmmount(WeatherUtility.getDouble(dayForecast, "qpf_allday", unitStrings.waterHeight)); + if (i == 0 && weather != null) { weather.temperature.setMinTemp(df.forecastTemp.min); weather.temperature.setMaxTemp(df.forecastTemp.max); @@ -247,11 +225,9 @@ private WeatherForecast parseForecast(JSONObject root, Weather weather) throws J forecast.addForecast(df); } - forecast.setUnit(units); return forecast; } - public List getCityResultList(String data) throws WeatherLibException { try { final List cityList = new ArrayList(); @@ -282,6 +258,7 @@ public List getCityResultList(String data) throws WeatherLibException { public WeatherHourForecast getHourForecastWeather(String data) throws WeatherLibException { try { final WeatherHourForecast forecast = new WeatherHourForecast(); + forecast.setUnit(units); final JSONObject jObj = new JSONObject(data); final JSONArray jHoursArray = jObj.getJSONArray("hourly_forecast"); @@ -319,6 +296,7 @@ public WeatherHourForecast getHourForecastWeather(String data) throws WeatherLib public HistoricalWeather getHistoricalWeather(String data) throws WeatherLibException { try { final HistoricalWeather histWeather = new HistoricalWeather(); + histWeather.setUnit(units); final JSONObject jObj = new JSONObject(data); final JSONObject histObj = jObj.getJSONObject("history"); @@ -373,8 +351,6 @@ public HistoricalWeather getHistoricalWeather(String data) throws WeatherLibExce histWeather.addHistoricalHourWeather(hhWeather); } - histWeather.setUnit(units); - return histWeather; } catch (JSONException json) { throw new WeatherLibException(json); @@ -385,6 +361,8 @@ public HistoricalWeather getHistoricalWeather(String data) throws WeatherLibExce public void setConfig(WeatherConfig config) { this.config = config; units = WeatherUtility.createWeatherUnit(config.unitSystem); + + unitStrings = WeatherUtility.isMetric(config.unitSystem) ? new MetricUnits() : new ImperialUnits(); } @Override @@ -471,8 +449,40 @@ public String getQueryHourForecastWeatherURL(WeatherRequest request) throws ApiK @Override public String getQueryHistoricalWeatherURL(WeatherRequest request, Date startDate, Date endDate) throws ApiKeyRequiredException { - final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH); return buildURL(request, "history_" + sdf.format(startDate)); } + + private class MetricUnits extends Units{ + public MetricUnits(){ + super("celsius", "c", "km", "kph", "cm", "mm", "mb"); + } + } + + private class ImperialUnits extends Units{ + public ImperialUnits(){ + super("fahrenheit", "f", "mi", "mph", "in", "in", "in"); + } + } + + private class Units{ + public final String temperature; + public final String temperatureShort; + public final String distance; + public final String speed; + public final String snowHeight; + public final String waterHeight; + public final String pressure; + + public Units(String temperature, String temperatureShort, String distance, String speed, String snowHeight, String waterHeight, String pressure){ + this.temperature = temperature; + this.temperatureShort = temperatureShort; + this.distance = distance; + this.speed = speed; + this.snowHeight = snowHeight; + this.waterHeight = waterHeight; + this.pressure = pressure; + } + } }