44506c674ed2fbcef12e0647bee05c23c90e3fac
[Sunshine.git] / app / src / main / java / uk / me / njae / sunshine / FetchWeatherTask.java
1 package uk.me.njae.sunshine;
2
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;
14
15 import org.json.JSONArray;
16 import org.json.JSONException;
17 import org.json.JSONObject;
18
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;
24 import java.net.URL;
25 import java.text.SimpleDateFormat;
26 import java.util.Date;
27 import java.util.Vector;
28
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;
32
33 /**
34 * Created by neil on 09/11/14.
35 */
36
37
38 public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
39
40 private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
41
42 private ArrayAdapter<String> mForecastAdapter;
43 private final Context mContext;
44
45 public FetchWeatherTask(Context context, ArrayAdapter<String> forecastAdapter) {
46 mContext = context;
47 mForecastAdapter = forecastAdapter;
48 }
49
50 private boolean DEBUG = true;
51
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.
54 */
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();
61 }
62
63 /**
64 * Prepare the weather high/lows for presentation.
65 */
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));
77
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);
83 }
84
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);
88
89 String highLowStr = roundedHigh + "/" + roundedLow;
90 return highLowStr;
91 }
92
93 /**
94 * Helper method to handle insertion of a new location in the weather database.
95 *
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.
101 */
102 private long addLocation(String locationSetting, String cityName, double lat, double lon) {
103
104 Log.v(LOG_TAG, "inserting " + cityName + ", with coord: " + lat + ", " + lon);
105
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},
112 null);
113
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);
118 } else {
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);
125
126 Uri locationInsertUri = mContext.getContentResolver()
127 .insert(LocationEntry.CONTENT_URI, locationValues);
128
129 return ContentUris.parseId(locationInsertUri);
130 }
131 }
132
133 /**
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.
136 * <p/>
137 * Fortunately parsing is easy: constructor takes the JSON string and converts it
138 * into an Object hierarchy for us.
139 */
140 private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays,
141 String locationSetting)
142 throws JSONException {
143
144 // These are the names of the JSON objects that need to be extracted.
145
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";
152
153 // Weather information. Each day's forecast info is an element of the "list" array.
154 final String OWM_LIST = "list";
155
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";
161
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";
166
167 final String OWM_WEATHER = "weather";
168 final String OWM_DESCRIPTION = "main";
169 final String OWM_WEATHER_ID = "id";
170
171 JSONObject forecastJson = new JSONObject(forecastJsonStr);
172 JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
173
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);
179
180 Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude);
181
182 // Insert the location into the database.
183 long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);
184
185 // Get and insert the new weather information into the database
186 Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());
187
188 String[] resultStrs = new String[numDays];
189 for (int i = 0; i < weatherArray.length(); i++) {
190 // These are the values that will be collected.
191
192 long dateTime;
193 double pressure;
194 int humidity;
195 double windSpeed;
196 double windDirection;
197
198 double high;
199 double low;
200
201 String description;
202 int weatherId;
203
204 // Get the JSON object representing the day
205 JSONObject dayForecast = weatherArray.getJSONObject(i);
206
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
209 // "this saturday".
210 dateTime = dayForecast.getLong(OWM_DATETIME);
211
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);
216
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);
223
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);
229
230 ContentValues weatherValues = new ContentValues();
231
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);
243
244 cVVector.add(weatherValues);
245
246 String highAndLow = formatHighLows(high, low);
247 String day = getReadableDateString(dateTime);
248 resultStrs[i] = day + " - " + description + " - " + highAndLow;
249 }
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.
259 if (DEBUG) {
260 Cursor weatherCursor = mContext.getContentResolver().query(
261 WeatherEntry.CONTENT_URI,
262 null,
263 null,
264 null,
265 null
266 );
267
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));
274 }
275 } else {
276 Log.v(LOG_TAG, "Query failed! :( **********");
277 }
278 }
279 }
280 return resultStrs;
281 }
282
283 @Override
284 protected String[] doInBackground(String... params) {
285
286 // If there's no zip code, there's nothing to look up. Verify size of params.
287 if (params.length == 0) {
288 return null;
289 }
290 String locationQuery = params[0];
291
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;
296
297 // Will contain the raw JSON response as a string.
298 String forecastJsonStr = null;
299
300 String format = "json";
301 String units = "metric";
302 int numDays = 14;
303
304 try {
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";
314
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))
320 .build();
321
322 URL url = new URL(builtUri.toString());
323
324 // Create the request to OpenWeatherMap, and open the connection
325 urlConnection = (HttpURLConnection) url.openConnection();
326 urlConnection.setRequestMethod("GET");
327 urlConnection.connect();
328
329 // Read the input stream into a String
330 InputStream inputStream = urlConnection.getInputStream();
331 StringBuffer buffer = new StringBuffer();
332 if (inputStream == null) {
333 // Nothing to do.
334 return null;
335 }
336 reader = new BufferedReader(new InputStreamReader(inputStream));
337
338 String line;
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");
344 }
345
346 if (buffer.length() == 0) {
347 // Stream was empty. No point in parsing.
348 return null;
349 }
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
354 // to parse it.
355 return null;
356 } finally {
357 if (urlConnection != null) {
358 urlConnection.disconnect();
359 }
360 if (reader != null) {
361 try {
362 reader.close();
363 } catch (final IOException e) {
364 Log.e(LOG_TAG, "Error closing stream", e);
365 }
366 }
367 }
368
369 try {
370 return getWeatherDataFromJson(forecastJsonStr, numDays, locationQuery);
371 } catch (JSONException e) {
372 Log.e(LOG_TAG, e.getMessage(), e);
373 e.printStackTrace();
374 }
375 // This will only happen if there was an error getting or parsing the forecast.
376 return null;
377 }
378
379 @Override
380 protected void onPostExecute(String[] result) {
381 if (result != null) {
382 mForecastAdapter.clear();
383 for (String dayForecastStr : result) {
384 mForecastAdapter.add(dayForecastStr);
385 }
386 // New data is back from the server. Hooray!
387 }
388 }
389
390 }