1 package uk
.me
.njae
.sunshine
;
3 import android
.content
.ContentUris
;
4 import android
.content
.ContentValues
;
5 import android
.content
.Context
;
6 import android
.content
.SharedPreferences
;
7 import android
.database
.Cursor
;
8 import android
.database
.DatabaseUtils
;
9 import android
.net
.Uri
;
10 import android
.os
.AsyncTask
;
11 import android
.preference
.PreferenceManager
;
12 import android
.util
.Log
;
13 import android
.widget
.ArrayAdapter
;
15 import org
.json
.JSONArray
;
16 import org
.json
.JSONException
;
17 import org
.json
.JSONObject
;
19 import java
.io
.BufferedReader
;
20 import java
.io
.IOException
;
21 import java
.io
.InputStream
;
22 import java
.io
.InputStreamReader
;
23 import java
.net
.HttpURLConnection
;
25 import java
.text
.SimpleDateFormat
;
26 import java
.util
.Date
;
27 import java
.util
.Vector
;
29 import uk
.me
.njae
.sunshine
.data
.WeatherContract
;
30 import uk
.me
.njae
.sunshine
.data
.WeatherContract
.LocationEntry
;
31 import uk
.me
.njae
.sunshine
.data
.WeatherContract
.WeatherEntry
;
34 * Created by neil on 09/11/14.
38 public class FetchWeatherTask
extends AsyncTask
<String
, Void
, String
[]> {
40 private final String LOG_TAG
= FetchWeatherTask
.class.getSimpleName();
42 private ArrayAdapter
<String
> mForecastAdapter
;
43 private final Context mContext
;
45 public FetchWeatherTask(Context context
, ArrayAdapter
<String
> forecastAdapter
) {
47 mForecastAdapter
= forecastAdapter
;
50 private boolean DEBUG
= true;
52 /* The date/time conversion code is going to be moved outside the asynctask later,
53 * so for convenience we're breaking it out into its own method now.
55 private String
getReadableDateString(long time
) {
56 // Because the API returns a unix timestamp (measured in seconds),
57 // it must be converted to milliseconds in order to be converted to valid date.
58 Date date
= new Date(time
* 1000);
59 SimpleDateFormat format
= new SimpleDateFormat("E, MMM d");
60 return format
.format(date
).toString();
64 * Prepare the weather high/lows for presentation.
66 private String
formatHighLows(double high
, double low
) {
67 // Data is fetched in Celsius by default.
68 // If user prefers to see in Fahrenheit, convert the values here.
69 // We do this rather than fetching in Fahrenheit so that the user can
70 // change this option without us having to re-fetch the data once
71 // we start storing the values in a database.
72 SharedPreferences sharedPrefs
=
73 PreferenceManager
.getDefaultSharedPreferences(mContext
);
74 String unitType
= sharedPrefs
.getString(
75 mContext
.getString(R
.string
.pref_units_key
),
76 mContext
.getString(R
.string
.pref_units_metric
));
78 if (unitType
.equals(mContext
.getString(R
.string
.pref_units_imperial
))) {
79 high
= (high
* 1.8) + 32;
80 low
= (low
* 1.8) + 32;
81 } else if (!unitType
.equals(mContext
.getString(R
.string
.pref_units_metric
))) {
82 Log
.d(LOG_TAG
, "Unit type not found: " + unitType
);
85 // For presentation, assume the user doesn't care about tenths of a degree.
86 long roundedHigh
= Math
.round(high
);
87 long roundedLow
= Math
.round(low
);
89 String highLowStr
= roundedHigh
+ "/" + roundedLow
;
94 * Helper method to handle insertion of a new location in the weather database.
96 * @param locationSetting The location string used to request updates from the server.
97 * @param cityName A human-readable city name, e.g "Mountain View"
98 * @param lat the latitude of the city
99 * @param lon the longitude of the city
100 * @return the row ID of the added location.
102 private long addLocation(String locationSetting
, String cityName
, double lat
, double lon
) {
104 Log
.v(LOG_TAG
, "inserting " + cityName
+ ", with coord: " + lat
+ ", " + lon
);
106 // First, check if the location with this city name exists in the db
107 Cursor cursor
= mContext
.getContentResolver().query(
108 LocationEntry
.CONTENT_URI
,
109 new String
[]{LocationEntry
._ID
},
110 LocationEntry
.COLUMN_LOCATION_SETTING
+ " = ?",
111 new String
[]{locationSetting
},
114 if (cursor
.moveToFirst()) {
115 Log
.v(LOG_TAG
, "Found it in the database!");
116 int locationIdIndex
= cursor
.getColumnIndex(LocationEntry
._ID
);
117 return cursor
.getLong(locationIdIndex
);
119 Log
.v(LOG_TAG
, "Didn't find it in the database, inserting now!");
120 ContentValues locationValues
= new ContentValues();
121 locationValues
.put(LocationEntry
.COLUMN_LOCATION_SETTING
, locationSetting
);
122 locationValues
.put(LocationEntry
.COLUMN_CITY_NAME
, cityName
);
123 locationValues
.put(LocationEntry
.COLUMN_COORD_LAT
, lat
);
124 locationValues
.put(LocationEntry
.COLUMN_COORD_LONG
, lon
);
126 Uri locationInsertUri
= mContext
.getContentResolver()
127 .insert(LocationEntry
.CONTENT_URI
, locationValues
);
129 return ContentUris
.parseId(locationInsertUri
);
134 * Take the String representing the complete forecast in JSON Format and
135 * pull out the data we need to construct the Strings needed for the wireframes.
137 * Fortunately parsing is easy: constructor takes the JSON string and converts it
138 * into an Object hierarchy for us.
140 private String
[] getWeatherDataFromJson(String forecastJsonStr
, int numDays
,
141 String locationSetting
)
142 throws JSONException
{
144 // These are the names of the JSON objects that need to be extracted.
146 // Location information
147 final String OWM_CITY
= "city";
148 final String OWM_CITY_NAME
= "name";
149 final String OWM_COORD
= "coord";
150 final String OWM_COORD_LAT
= "lat";
151 final String OWM_COORD_LONG
= "lon";
153 // Weather information. Each day's forecast info is an element of the "list" array.
154 final String OWM_LIST
= "list";
156 final String OWM_DATETIME
= "dt";
157 final String OWM_PRESSURE
= "pressure";
158 final String OWM_HUMIDITY
= "humidity";
159 final String OWM_WINDSPEED
= "speed";
160 final String OWM_WIND_DIRECTION
= "deg";
162 // All temperatures are children of the "temp" object.
163 final String OWM_TEMPERATURE
= "temp";
164 final String OWM_MAX
= "max";
165 final String OWM_MIN
= "min";
167 final String OWM_WEATHER
= "weather";
168 final String OWM_DESCRIPTION
= "main";
169 final String OWM_WEATHER_ID
= "id";
171 JSONObject forecastJson
= new JSONObject(forecastJsonStr
);
172 JSONArray weatherArray
= forecastJson
.getJSONArray(OWM_LIST
);
174 JSONObject cityJson
= forecastJson
.getJSONObject(OWM_CITY
);
175 String cityName
= cityJson
.getString(OWM_CITY_NAME
);
176 JSONObject coordJSON
= cityJson
.getJSONObject(OWM_COORD
);
177 double cityLatitude
= coordJSON
.getLong(OWM_COORD_LAT
);
178 double cityLongitude
= coordJSON
.getLong(OWM_COORD_LONG
);
180 Log
.v(LOG_TAG
, cityName
+ ", with coord: " + cityLatitude
+ " " + cityLongitude
);
182 // Insert the location into the database.
183 long locationID
= addLocation(locationSetting
, cityName
, cityLatitude
, cityLongitude
);
185 // Get and insert the new weather information into the database
186 Vector
<ContentValues
> cVVector
= new Vector
<ContentValues
>(weatherArray
.length());
188 String
[] resultStrs
= new String
[numDays
];
189 for (int i
= 0; i
< weatherArray
.length(); i
++) {
190 // These are the values that will be collected.
196 double windDirection
;
204 // Get the JSON object representing the day
205 JSONObject dayForecast
= weatherArray
.getJSONObject(i
);
207 // The date/time is returned as a long. We need to convert that
208 // into something human-readable, since most people won't read "1400356800" as
210 dateTime
= dayForecast
.getLong(OWM_DATETIME
);
212 pressure
= dayForecast
.getDouble(OWM_PRESSURE
);
213 humidity
= dayForecast
.getInt(OWM_HUMIDITY
);
214 windSpeed
= dayForecast
.getDouble(OWM_WINDSPEED
);
215 windDirection
= dayForecast
.getDouble(OWM_WIND_DIRECTION
);
217 // Description is in a child array called "weather", which is 1 element long.
218 // That element also contains a weather code.
219 JSONObject weatherObject
=
220 dayForecast
.getJSONArray(OWM_WEATHER
).getJSONObject(0);
221 description
= weatherObject
.getString(OWM_DESCRIPTION
);
222 weatherId
= weatherObject
.getInt(OWM_WEATHER_ID
);
224 // Temperatures are in a child object called "temp". Try not to name variables
225 // "temp" when working with temperature. It confuses everybody.
226 JSONObject temperatureObject
= dayForecast
.getJSONObject(OWM_TEMPERATURE
);
227 high
= temperatureObject
.getDouble(OWM_MAX
);
228 low
= temperatureObject
.getDouble(OWM_MIN
);
230 ContentValues weatherValues
= new ContentValues();
232 weatherValues
.put(WeatherEntry
.COLUMN_LOC_KEY
, locationID
);
233 weatherValues
.put(WeatherEntry
.COLUMN_DATETEXT
,
234 WeatherContract
.getDbDateString(new Date(dateTime
* 1000L)));
235 weatherValues
.put(WeatherEntry
.COLUMN_HUMIDITY
, humidity
);
236 weatherValues
.put(WeatherEntry
.COLUMN_PRESSURE
, pressure
);
237 weatherValues
.put(WeatherEntry
.COLUMN_WIND_SPEED
, windSpeed
);
238 weatherValues
.put(WeatherEntry
.COLUMN_DEGREES
, windDirection
);
239 weatherValues
.put(WeatherEntry
.COLUMN_MAX_TEMP
, high
);
240 weatherValues
.put(WeatherEntry
.COLUMN_MIN_TEMP
, low
);
241 weatherValues
.put(WeatherEntry
.COLUMN_SHORT_DESC
, description
);
242 weatherValues
.put(WeatherEntry
.COLUMN_WEATHER_ID
, weatherId
);
244 cVVector
.add(weatherValues
);
246 String highAndLow
= formatHighLows(high
, low
);
247 String day
= getReadableDateString(dateTime
);
248 resultStrs
[i
] = day
+ " - " + description
+ " - " + highAndLow
;
250 if (cVVector
.size() > 0) {
251 ContentValues
[] cvArray
= new ContentValues
[cVVector
.size()];
252 cVVector
.toArray(cvArray
);
253 int rowsInserted
= mContext
.getContentResolver()
254 .bulkInsert(WeatherEntry
.CONTENT_URI
, cvArray
);
255 Log
.v(LOG_TAG
, "inserted " + rowsInserted
+ " rows of weather data");
256 // Use a DEBUG variable to gate whether or not you do this, so you can easily
257 // turn it on and off, and so that it's easy to see what you can rip out if
258 // you ever want to remove it.
260 Cursor weatherCursor
= mContext
.getContentResolver().query(
261 WeatherEntry
.CONTENT_URI
,
268 if (weatherCursor
.moveToFirst()) {
269 ContentValues resultValues
= new ContentValues();
270 DatabaseUtils
.cursorRowToContentValues(weatherCursor
, resultValues
);
271 Log
.v(LOG_TAG
, "Query succeeded! **********");
272 for (String key
: resultValues
.keySet()) {
273 Log
.v(LOG_TAG
, key
+ ": " + resultValues
.getAsString(key
));
276 Log
.v(LOG_TAG
, "Query failed! :( **********");
284 protected String
[] doInBackground(String
... params
) {
286 // If there's no zip code, there's nothing to look up. Verify size of params.
287 if (params
.length
== 0) {
290 String locationQuery
= params
[0];
292 // These two need to be declared outside the try/catch
293 // so that they can be closed in the finally block.
294 HttpURLConnection urlConnection
= null;
295 BufferedReader reader
= null;
297 // Will contain the raw JSON response as a string.
298 String forecastJsonStr
= null;
300 String format
= "json";
301 String units
= "metric";
305 // Construct the URL for the OpenWeatherMap query
306 // Possible parameters are avaiable at OWM's forecast API page, at
307 // http://openweathermap.org/API#forecast
308 final String FORECAST_BASE_URL
=
309 "http://api.openweathermap.org/data/2.5/forecast/daily?";
310 final String QUERY_PARAM
= "q";
311 final String FORMAT_PARAM
= "mode";
312 final String UNITS_PARAM
= "units";
313 final String DAYS_PARAM
= "cnt";
315 Uri builtUri
= Uri
.parse(FORECAST_BASE_URL
).buildUpon()
316 .appendQueryParameter(QUERY_PARAM
, params
[0])
317 .appendQueryParameter(FORMAT_PARAM
, format
)
318 .appendQueryParameter(UNITS_PARAM
, units
)
319 .appendQueryParameter(DAYS_PARAM
, Integer
.toString(numDays
))
322 URL url
= new URL(builtUri
.toString());
324 // Create the request to OpenWeatherMap, and open the connection
325 urlConnection
= (HttpURLConnection
) url
.openConnection();
326 urlConnection
.setRequestMethod("GET");
327 urlConnection
.connect();
329 // Read the input stream into a String
330 InputStream inputStream
= urlConnection
.getInputStream();
331 StringBuffer buffer
= new StringBuffer();
332 if (inputStream
== null) {
336 reader
= new BufferedReader(new InputStreamReader(inputStream
));
339 while ((line
= reader
.readLine()) != null) {
340 // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
341 // But it does make debugging a *lot* easier if you print out the completed
342 // buffer for debugging.
343 buffer
.append(line
+ "\n");
346 if (buffer
.length() == 0) {
347 // Stream was empty. No point in parsing.
350 forecastJsonStr
= buffer
.toString();
351 } catch (IOException e
) {
352 Log
.e(LOG_TAG
, "Error ", e
);
353 // If the code didn't successfully get the weather data, there's no point in attemping
357 if (urlConnection
!= null) {
358 urlConnection
.disconnect();
360 if (reader
!= null) {
363 } catch (final IOException e
) {
364 Log
.e(LOG_TAG
, "Error closing stream", e
);
370 return getWeatherDataFromJson(forecastJsonStr
, numDays
, locationQuery
);
371 } catch (JSONException e
) {
372 Log
.e(LOG_TAG
, e
.getMessage(), e
);
375 // This will only happen if there was an error getting or parsing the forecast.
380 protected void onPostExecute(String
[] result
) {
381 if (result
!= null) {
382 mForecastAdapter
.clear();
383 for (String dayForecastStr
: result
) {
384 mForecastAdapter
.add(dayForecastStr
);
386 // New data is back from the server. Hooray!