diff --git a/OkHttpClient/build.gradle b/OkHttpClient/build.gradle index a0e129e..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 @@ -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/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/build.gradle b/build.gradle index 074a2fc..7c5436a 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' } } @@ -14,6 +13,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 @@ -25,8 +32,7 @@ allprojects { ext { compileSdkVersion = 19 - buildToolsVersion = "21.0.1" + buildToolsVersion = "25.0.2" } - apply plugin: 'android-reporting' \ No newline at end of file diff --git a/demo/build.gradle b/demo/build.gradle index f40ac01..110d5d0 100644 --- a/demo/build.gradle +++ b/demo/build.gradle @@ -1,5 +1,4 @@ -apply plugin: 'android-sdk-manager' -apply plugin: 'android' +apply plugin: 'com.android.application' android { 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/demo15/build.gradle b/demo15/build.gradle index eb71c23..a300ad0 100644 --- a/demo15/build.gradle +++ b/demo15/build.gradle @@ -1,5 +1,4 @@ -apply plugin: 'android-sdk-manager' -apply plugin: 'android' +apply plugin: 'com.android.application' repositories { mavenCentral() diff --git a/gradle.properties b/gradle.properties index ab3d441..90e5ea0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,14 +1,16 @@ -VERSION_NAME=1.6.0 +VERSION_NAME=1.6.1-SNAPSHOT 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/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 diff --git a/lib/build.gradle b/lib/build.gradle index ce81efe..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 @@ -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/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/City.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/model/City.java index 163af16..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 @@ -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; } @@ -162,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/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/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..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 @@ -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; } @@ -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 0e1e974..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); } @@ -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() ; } @@ -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 95e19d9..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 @@ -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; @@ -50,7 +49,7 @@ import java.util.Date; import java.util.GregorianCalendar; import java.util.List; - +import java.util.Locale; /** @@ -61,44 +60,39 @@ 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 BaseWeather.WeatherUnit units; + private Units unitStrings; private IWeatherCodeProvider codeProvider; - private WeatherForecast forecast = new WeatherForecast(); public CurrentWeather getCurrentCondition(String data) throws WeatherLibException { - //Log.d("SwA", "JSON CurrentWeather [" + data + "]"); - CurrentWeather cWeather = new CurrentWeather(); - Weather weather = new Weather(); try { - // We create out JSONObject from the data - JSONObject rootObj = new JSONObject(data); - JSONObject jObj = getObject("current_observation", rootObj); - - // We start extracting the info - - 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)); + final CurrentWeather currentWeather = new CurrentWeather(); + currentWeather.setUnit(units); + + final Weather weather = new Weather(); + currentWeather.weather = weather; + + final JSONObject rootObj = new JSONObject(data); + final JSONObject jObj = rootObj.getJSONObject("current_observation"); + 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")); + 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")); + // WeatherCode: Convert to internal code if (codeProvider != null) { try { weather.currentCondition.setWeatherCode(codeProvider.getWeatherCode(weather.currentCondition.getIcon())); @@ -107,112 +101,104 @@ 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)) - trendVal = 0; - else - trendVal = Integer.parseInt(trend); - - weather.currentCondition.setPressureTrend(trendVal); - weather.currentCondition.setUV(getFloat("UV", jObj)); - weather.currentCondition.setSolarRadiation(getString("solarradiation", jObj)); - - 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)); - } 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)); + + // Humidity + 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) { + // + } } - parseForecast(rootObj, weather); + // 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)); + + + // 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", Locale.ENGLISH); + + 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) { + // + } + } } - + return currentWeather; } 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); - parseForecast(rootObj, null); + final JSONObject rootObj = new JSONObject(data); + + return parseForecast(rootObj, null); } catch (JSONException json) { - json.printStackTrace(); throw new WeatherLibException(json); } - return forecast; } - private void 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"); + private WeatherForecast parseForecast(JSONObject root, Weather weather) throws JSONException { + final JSONObject jsonForecast = root.getJSONObject("forecast"); + final JSONObject simpleForecast = jsonForecast.getJSONObject("simpleforecast"); + final JSONArray jArr = simpleForecast.getJSONArray("forecastday"); + + final WeatherForecast forecast = new WeatherForecast(); + forecast.setUnit(units); 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(); - df.weather.currentCondition.setDescr(dayForecast.getString("conditions")); - df.weather.currentCondition.setIcon(dayForecast.getString("icon")); + final JSONObject dayForecast = jArr.getJSONObject(i); + + 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 { @@ -222,25 +208,15 @@ private void parseForecast(JSONObject root, Weather weather) throws JSONExceptio } } - 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.weather.snow.setTime("Day"); - df.weather.snow.setAmmount(dayForecast.getJSONObject("snow_allday").getInt("cm")); - df.weather.rain[0].setTime("Day"); - df.weather.rain[0].setAmmount(dayForecast.getJSONObject("qpf_allday").getInt("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.weather.snow.setTime("Day"); - df.weather.snow.setAmmount(dayForecast.getJSONObject("snow_allday").getInt("in")); - df.weather.rain[0].setTime("Day"); - df.weather.rain[0].setAmmount(dayForecast.getJSONObject("qpf_allday").getInt("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)); - df.weather.wind.setDeg(dayForecast.getJSONObject("avewind").getInt("degrees")); if (i == 0 && weather != null) { weather.temperature.setMinTemp(df.forecastTemp.min); weather.temperature.setMaxTemp(df.forecastTemp.max); @@ -249,138 +225,123 @@ private void parseForecast(JSONObject root, Weather weather) throws JSONExceptio forecast.addForecast(df); } - forecast.setUnit(units); + return forecast; } - public List getCityResultList(String data) throws WeatherLibException { - List cityList = new ArrayList(); - // Log.d("SwA", "Data ["+data+"]"); try { + final List cityList = new ArrayList(); - 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"); - //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(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(); + forecast.setUnit(units); + + 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(); + histWeather.setUnit(units); + + 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); } @@ -388,24 +349,20 @@ public HistoricalWeather getHistoricalWeather(String data) throws WeatherLibExce // fog, hail, tornado and so on still not supported histWeather.addHistoricalHourWeather(hhWeather); - } + return histWeather; + } catch (JSONException json) { + throw new WeatherLibException(json); } - catch(JSONException json) { - throw new WeatherLibException(json); - } - - - histWeather.setUnit(units); - - return histWeather; } @Override public void setConfig(WeatherConfig config) { this.config = config; units = WeatherUtility.createWeatherUnit(config.unitSystem); + + unitStrings = WeatherUtility.isMetric(config.unitSystem) ? new MetricUnits() : new ImperialUnits(); } @Override @@ -418,49 +375,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; @@ -468,34 +387,17 @@ 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(); 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) @@ -508,95 +410,79 @@ 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 String buildURL(final WeatherRequest request, final String type) throws ApiKeyRequiredException{ + if (config.ApiKey == null) { + throw new ApiKeyRequiredException(); + } - private float getFloat(String tagName, JSONObject jObj) throws JSONException { - try { - return (float) jObj.getDouble(tagName); - } catch (Throwable t) { - return -1; + String location = request.getCityId(); + if (location == null) { + location = request.getLat() + "," + request.getLon(); } - } - private int getInt(String tagName, JSONObject jObj) throws JSONException { - return jObj.getInt(tagName); - } + String language = "EN"; + if (config.lang != null) { + language = config.lang.toUpperCase(); + } - private String addLanguage(String url) { - if (config.lang == null) - return url; + final String url = String.format("%s/%s/%s/lang:%s/q/%s.json", BASE_URL_ID, config.ApiKey, type, language, location); - String nUrl = url + "/lang:" + config.lang.toUpperCase() + "/"; - return nUrl; + 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", Locale.ENGLISH); + + return buildURL(request, "history_" + sdf.format(startDate)); + } - 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"; + private class MetricUnits extends Units{ + public MetricUnits(){ + super("celsius", "c", "km", "kph", "cm", "mm", "mb"); + } + } - return url; + 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; + } } } 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..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 @@ -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; @@ -39,18 +40,18 @@ 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; import java.util.List; import java.util.Locale; -import java.util.UnknownFormatConversionException; - 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_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; @@ -76,22 +77,20 @@ 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")) { // 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) { + + } 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 +100,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); } @@ -109,8 +108,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); } @@ -124,123 +121,29 @@ 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 + "]"); - CurrentWeather cWeather = new CurrentWeather(); - 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(); - - 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"))); - } 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"))); - } 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"))); - isFirstDayForecast = false; - } - } else if (tagName.equals("yweather:condition")) { - // Log.d("SwA", "Tag [Condition]"); - weather.currentCondition.setWeatherId(Integer.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(Integer.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); - 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()); - } - - } - - } 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); - } - - cWeather.setUnit(units); - cWeather.weather = weather; - return cWeather; + return getWeather(data).first; } @Override public String getQueryCityURL(String cityNamePattern) throws ApiKeyRequiredException { + // Wildcard to enable completion + return getQueryCityURLFromString(cityNamePattern + "*"); + } - if (config.ApiKey == null) - throw new ApiKeyRequiredException(); + 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"; } /* @@ -270,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; + public String getQueryCityURLByCoord(double lat, double lon) throws ApiKeyRequiredException { + return getQueryCityURLFromString(lat + ", " + lon); } @Override @@ -298,28 +195,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)); - String tagName = null; - String currentTag = null; - int event = parser.getEventType(); boolean isFirstDayForecast = true; + String text = null; + 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"))); + if (tagName.equals("yweather:wind")) { + 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(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(parseFloat(parser.getAttributeValue(null, "low"))); + current.temperature.setMaxTemp(parseFloat(parser.getAttributeValue(null, "high"))); + isFirstDayForecast = false; + } + DayForecast df = new DayForecast(); + 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 { df.weather.currentCondition.setWeatherCode(codeProvider.getWeatherCode(String.valueOf(df.weather.currentCondition.getWeatherId()))); @@ -332,30 +249,78 @@ 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:condition")) { + current.currentCondition.setWeatherId(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(parseFloat(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")) { - // 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) { - if ("image".equals(currentTag)) { - currentTag = null; + } + else if (event == XmlPullParser.TEXT) { + text = parser.getText(); + } + else if (event == XmlPullParser.END_TAG) { + if (tagName.equals("geo:lat")){ + current.location.setLatitude(parseFloat(text)); + } else if (tagName.equals("geo:long")){ + current.location.setLongitude(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) { @@ -390,22 +355,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 @@ -417,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/request/WeatherRequest.java b/lib/src/main/java/com/survivingwithandroid/weather/lib/request/WeatherRequest.java index 05da72f..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(double lon, double lat) { - this.lon = lon; + public WeatherRequest(Location location) { + this.lat = location.getLatitude(); + this.lon = location.getLongitude(); + } + + public WeatherRequest(double lat, double lon) { this.lat = lat; + this.lon = lon; } public String getCityId() { 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..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,13 +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; + + for (int i = 0; i < lastIndex; i++) { + last = last.getJSONObject(names[i]); + } - public static float string2Float(String value) { - if (value == null || "".equals(value)) - return -1; + return last; + } - return Float.parseFloat(value); + 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 Integer getInteger(final JSONObject json, final String... names){ + try{ + return getLast(json, names).getInt(names[names.length - 1]); + } + catch (JSONException e){ + return DefaultValues.ERROR_INTEGER; + } + } + 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 Double getDouble(final JSONObject json, final String... names){ + try{ + return getLast(json, names).getDouble(names[names.length - 1]); + } + catch (JSONException e){ + return DefaultValues.ERROR_DOUBLE; + } + } } diff --git a/nexus_push.gradle b/nexus_push.gradle new file mode 100644 index 0000000..349944c --- /dev/null +++ b/nexus_push.gradle @@ -0,0 +1,96 @@ +apply plugin: 'maven' + +def getRepositoryUsername() { + return hasProperty('nexusUsername') ? nexusUsername : "" +} + +def getRepositoryPassword() { + return hasProperty('nexusPassword') ? nexusPassword : "" +} + +def publishLocal() { + return hasProperty('local') +} + +afterEvaluate { project -> + uploadArchives { + repositories { + mavenDeployer { + pom.artifactId = POM_ARTIFACT_ID + + if(publishLocal()){ + def localMavenRepo = 'file://' + new File(System.getProperty('user.home'), '.m2/repository').absolutePath + repository(url: localMavenRepo) + } + else { + 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 { + 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 + } + } + } + } + } + } + + 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..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 @@ -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 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); }