a3ca249bb3556ccaafe94f8198c874cb07bac102
[JavaForFun] /
1 package de.example.exampletdd.fragment.overview;
2
3 import java.io.FileNotFoundException;
4 import java.io.IOException;
5 import java.net.MalformedURLException;
6 import java.net.URISyntaxException;
7 import java.net.URL;
8 import java.text.DecimalFormat;
9 import java.text.NumberFormat;
10 import java.text.SimpleDateFormat;
11 import java.util.ArrayList;
12 import java.util.Calendar;
13 import java.util.Date;
14 import java.util.List;
15 import java.util.Locale;
16
17 import org.apache.http.client.ClientProtocolException;
18
19 import android.app.DialogFragment;
20 import android.app.ListFragment;
21 import android.content.ComponentName;
22 import android.content.Intent;
23 import android.content.SharedPreferences;
24 import android.graphics.Bitmap;
25 import android.graphics.BitmapFactory;
26 import android.net.http.AndroidHttpClient;
27 import android.os.AsyncTask;
28 import android.os.Bundle;
29 import android.preference.PreferenceManager;
30 import android.util.Log;
31 import android.view.View;
32 import android.widget.ListView;
33
34 import com.fasterxml.jackson.core.JsonParseException;
35
36 import de.example.exampletdd.R;
37 import de.example.exampletdd.activityinterface.GetWeather;
38 import de.example.exampletdd.fragment.ErrorDialogFragment;
39 import de.example.exampletdd.fragment.ProgressDialogFragment;
40 import de.example.exampletdd.fragment.specific.WeatherInformationSpecificDataFragment;
41 import de.example.exampletdd.httpclient.CustomHTTPClient;
42 import de.example.exampletdd.model.GeocodingData;
43 import de.example.exampletdd.model.forecastweather.ForecastWeatherData;
44 import de.example.exampletdd.parser.IJPOSWeatherParser;
45 import de.example.exampletdd.parser.JPOSWeatherParser;
46 import de.example.exampletdd.service.WeatherServiceParser;
47 import de.example.exampletdd.service.WeatherServicePersistenceFile;
48
49 public class WeatherInformationOverviewFragment extends ListFragment implements GetWeather {
50     private boolean mIsFahrenheit;
51     private String mDayForecast;
52     private WeatherServicePersistenceFile mWeatherServicePersistenceFile;
53
54     @Override
55     public void onCreate(final Bundle savedInstanceState) {
56         super.onCreate(savedInstanceState);
57
58         final SharedPreferences sharedPreferences = PreferenceManager
59                 .getDefaultSharedPreferences(this.getActivity());
60         final String keyPreference = this.getResources().getString(
61                 R.string.weather_preferences_day_forecast_key);
62         this.mDayForecast = sharedPreferences.getString(keyPreference, "");
63
64         this.mWeatherServicePersistenceFile = new WeatherServicePersistenceFile(this.getActivity());
65         this.mWeatherServicePersistenceFile.removeForecastWeatherData();
66     }
67
68     @Override
69     public void onActivityCreated(final Bundle savedInstanceState) {
70         super.onActivityCreated(savedInstanceState);
71
72         final ListView listWeatherView = this.getListView();
73         listWeatherView.setChoiceMode(ListView.CHOICE_MODE_NONE);
74
75         if (savedInstanceState != null) {
76             // Restore state
77             final ForecastWeatherData forecastWeatherData = (ForecastWeatherData) savedInstanceState
78                     .getSerializable("ForecastWeatherData");
79
80             if (forecastWeatherData != null) {
81                 try {
82                     this.mWeatherServicePersistenceFile
83                     .storeForecastWeatherData(forecastWeatherData);
84                 } catch (final IOException e) {
85                     final DialogFragment newFragment = ErrorDialogFragment
86                             .newInstance(R.string.error_dialog_generic_error);
87                     newFragment.show(this.getFragmentManager(), "errorDialog");
88                 }
89             }
90         }
91
92         this.setHasOptionsMenu(false);
93
94         final WeatherOverviewAdapter adapter = new WeatherOverviewAdapter(
95                 this.getActivity(), R.layout.weather_main_entry_list);
96
97
98         this.setEmptyText("Press download to receive weather information");
99
100         this.setListAdapter(adapter);
101         this.setListShown(true);
102         this.setListShownNoAnimation(true);
103     }
104
105     @Override
106     public void onListItemClick(final ListView l, final View v, final int position, final long id) {
107         final WeatherInformationSpecificDataFragment fragment = (WeatherInformationSpecificDataFragment) this.getFragmentManager()
108                 .findFragmentById(R.id.weather_specific_data__fragment);
109         if (fragment == null) {
110             // handset layout
111             final Intent intent = new Intent("de.example.exampletdd.WEATHERINFO").
112                     setComponent(new ComponentName("de.example.exampletdd",
113                             "de.example.exampletdd.WeatherInformationSpecificDataActivity"));
114             intent.putExtra("CHOSEN_DAY", (int) id);
115             WeatherInformationOverviewFragment.this.getActivity().startActivity(intent);
116         } else {
117             // tablet layout
118             fragment.getWeatherByDay((int) id);
119         }
120     }
121
122     @Override
123     public void onSaveInstanceState(final Bundle savedInstanceState) {
124
125         // Save state
126         final ForecastWeatherData forecastWeatherData = this.mWeatherServicePersistenceFile
127                 .getForecastWeatherData();
128
129         if (forecastWeatherData != null) {
130             savedInstanceState.putSerializable("ForecastWeatherData", forecastWeatherData);
131         }
132
133         super.onSaveInstanceState(savedInstanceState);
134     }
135
136     @Override
137     public void getRemoteWeatherInformation() {
138
139         final GeocodingData geocodingData = this.mWeatherServicePersistenceFile.getGeocodingData();
140
141         if (geocodingData != null) {
142             final IJPOSWeatherParser JPOSWeatherParser = new JPOSWeatherParser();
143             final WeatherServiceParser weatherService = new WeatherServiceParser(
144                     JPOSWeatherParser);
145             final AndroidHttpClient httpClient = AndroidHttpClient
146                     .newInstance("Android Weather Information Agent");
147             final CustomHTTPClient HTTPweatherClient = new CustomHTTPClient(
148                     httpClient);
149
150             final ForecastWeatherTask weatherTask = new ForecastWeatherTask(HTTPweatherClient,
151                     weatherService);
152
153
154             weatherTask.execute(geocodingData);
155         }
156     }
157
158     @Override
159     public void getWeatherByDay(final int chosenDay) {
160         // Nothing to do.
161     }
162
163     public void updateForecastWeatherData(final ForecastWeatherData forecastWeatherData) {
164         final List<WeatherOverviewEntry> entries = new ArrayList<WeatherOverviewEntry>();
165         final WeatherOverviewAdapter adapter = new WeatherOverviewAdapter(this.getActivity(),
166                 R.layout.weather_main_entry_list);
167
168         final Bitmap picture = BitmapFactory.decodeResource(
169                 this.getResources(), R.drawable.ic_02d);
170         final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.getDefault());
171         tempFormatter.applyPattern("#####.##");
172         final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM d", Locale.getDefault());
173         final double tempUnits = this.mIsFahrenheit ? 0 : 273.15;
174         final String symbol = this.mIsFahrenheit ? "ºF" : "ºC";
175
176
177         final Calendar calendar = Calendar.getInstance();
178         for (final de.example.exampletdd.model.forecastweather.List forecast : forecastWeatherData
179                 .getList()) {
180
181
182             final Long forecastUNIXDate = (Long) forecast.getDt();
183             calendar.setTimeInMillis(forecastUNIXDate * 1000L);
184             final Date dayTime = calendar.getTime();
185             final String dayText = dateFormat.format(dayTime);
186
187             Double maxTemp = null;
188             if (forecast.getTemp().getMax() != null) {
189                 maxTemp = (Double) forecast.getTemp().getMax();
190                 maxTemp = maxTemp - tempUnits;
191             }
192
193             Double minTemp = null;
194             if (forecast.getTemp().getMin() != null) {
195                 minTemp = (Double) forecast.getTemp().getMin();
196                 minTemp = minTemp - tempUnits;
197             }
198
199             if ((maxTemp != null) && (minTemp != null)) {
200                 entries.add(new WeatherOverviewEntry(dayText, tempFormatter.format(maxTemp)
201                         + symbol, tempFormatter.format(minTemp) + symbol, picture));
202             }
203         }
204
205         this.setListAdapter(null);
206         adapter.addAll(entries);
207         this.setListAdapter(adapter);
208     }
209
210     @Override
211     public void onResume() {
212         super.onResume();
213
214         final SharedPreferences sharedPreferences = PreferenceManager
215                 .getDefaultSharedPreferences(this.getActivity());
216
217         // 1. Update units of measurement.
218         String keyPreference = this.getResources().getString(
219                 R.string.weather_preferences_units_key);
220         final String unitsPreferenceValue = sharedPreferences.getString(keyPreference, "");
221         final String celsius = this.getResources().getString(
222                 R.string.weather_preferences_units_celsius);
223         if (unitsPreferenceValue.equals(celsius)) {
224             this.mIsFahrenheit = false;
225         } else {
226             this.mIsFahrenheit = true;
227         }
228
229         // 2. Update number day forecast.
230         keyPreference = this.getResources().getString(
231                 R.string.weather_preferences_day_forecast_key);
232         this.mDayForecast = sharedPreferences.getString(keyPreference, "");
233
234
235         // 3. Update forecast weather data on display.
236         final ForecastWeatherData forecastWeatherData = this.mWeatherServicePersistenceFile
237                 .getForecastWeatherData();
238         if (forecastWeatherData != null) {
239             this.updateForecastWeatherData(forecastWeatherData);
240         }
241
242     }
243
244     public class ForecastWeatherTask extends AsyncTask<Object, Void, ForecastWeatherData> {
245         private static final String TAG = "ForecastWeatherTask";
246         private final CustomHTTPClient weatherHTTPClient;
247         private final WeatherServiceParser weatherService;
248         private final DialogFragment newFragment;
249
250         public ForecastWeatherTask(final CustomHTTPClient weatherHTTPClient,
251                 final WeatherServiceParser weatherService) {
252             this.weatherHTTPClient = weatherHTTPClient;
253             this.weatherService = weatherService;
254             this.newFragment = ProgressDialogFragment.newInstance(
255                     R.string.progress_dialog_get_remote_data,
256                     WeatherInformationOverviewFragment.this
257                     .getString(R.string.progress_dialog_generic_message));
258         }
259
260         @Override
261         protected void onPreExecute() {
262             this.newFragment.show(WeatherInformationOverviewFragment.this.getActivity()
263                     .getFragmentManager(), "progressDialog");
264         }
265
266         @Override
267         protected ForecastWeatherData doInBackground(final Object... params) {
268             ForecastWeatherData forecastWeatherData = null;
269
270             try {
271                 forecastWeatherData = this.doInBackgroundThrowable(params);
272             } catch (final ClientProtocolException e) {
273                 Log.e(TAG, "doInBackground exception: ", e);
274             } catch (final MalformedURLException e) {
275                 Log.e(TAG, "doInBackground exception: ", e);
276             } catch (final URISyntaxException e) {
277                 Log.e(TAG, "doInBackground exception: ", e);
278             } catch (final JsonParseException e) {
279                 Log.e(TAG, "doInBackground exception: ", e);
280             } catch (final IOException e) {
281                 // logger infrastructure swallows UnknownHostException :/
282                 Log.e(TAG, "doInBackground exception: " + e.getMessage(), e);
283             } finally {
284                 this.weatherHTTPClient.close();
285             }
286
287             return forecastWeatherData;
288         }
289
290         @Override
291         protected void onPostExecute(final ForecastWeatherData weatherData) {
292             this.weatherHTTPClient.close();
293
294             this.newFragment.dismiss();
295
296             if (weatherData != null) {
297                 try {
298                     this.onPostExecuteThrowable(weatherData);
299                 } catch (final IOException e) {
300                     Log.e(TAG, "WeatherTask onPostExecute exception: ", e);
301                     final DialogFragment newFragment = ErrorDialogFragment
302                             .newInstance(R.string.error_dialog_generic_error);
303                     newFragment.show(WeatherInformationOverviewFragment.this.getFragmentManager(), "errorDialog");
304                 }
305             } else {
306                 final DialogFragment newFragment = ErrorDialogFragment
307                         .newInstance(R.string.error_dialog_generic_error);
308                 newFragment.show(WeatherInformationOverviewFragment.this.getFragmentManager(), "errorDialog");
309             }
310         }
311
312         @Override
313         protected void onCancelled(final ForecastWeatherData weatherData) {
314             this.weatherHTTPClient.close();
315
316             final DialogFragment newFragment = ErrorDialogFragment
317                     .newInstance(R.string.error_dialog_connection_tiemout);
318             newFragment.show(WeatherInformationOverviewFragment.this.getFragmentManager(), "errorDialog");
319         }
320
321         private ForecastWeatherData doInBackgroundThrowable(final Object... params)
322                 throws ClientProtocolException, MalformedURLException,
323                 URISyntaxException, JsonParseException, IOException {
324             // final SharedPreferences sharedPreferences = PreferenceManager
325             // .getDefaultSharedPreferences(WeatherInformationOverviewFragment.this
326             // .getActivity());
327             //
328             // final String keyPreference =
329             // WeatherInformationOverviewFragment.this
330             // .getActivity().getString(
331             // R.string.weather_preferences_language_key);
332             // final String languagePreferenceValue =
333             // sharedPreferences.getString(keyPreference, "");
334
335             // 1. Coordinates
336             final GeocodingData geocodingData = (GeocodingData) params[0];
337
338
339             final String APIVersion = WeatherInformationOverviewFragment.this.getResources()
340                     .getString(R.string.api_version);
341             // 2. Forecast
342             final String urlAPI = WeatherInformationOverviewFragment.this.getResources()
343                     .getString(R.string.uri_api_weather_forecast);
344             final String url = this.weatherService.createURIAPIForecastWeather(urlAPI, APIVersion,
345                     geocodingData.getLatitude(), geocodingData.getLongitude(), WeatherInformationOverviewFragment.this.mDayForecast);
346             final String jsonData = this.weatherHTTPClient.retrieveDataAsString(new URL(url));
347             final ForecastWeatherData forecastWeatherData = this.weatherService
348                     .retrieveForecastWeatherDataFromJPOS(jsonData);
349
350             return forecastWeatherData;
351         }
352
353         private void onPostExecuteThrowable(final ForecastWeatherData forecastWeatherData)
354                 throws FileNotFoundException, IOException {
355             WeatherInformationOverviewFragment.this.mWeatherServicePersistenceFile
356             .storeForecastWeatherData(forecastWeatherData);
357
358             WeatherInformationOverviewFragment.this.updateForecastWeatherData(forecastWeatherData);
359         }
360     }
361 }