1 package de.example.exampletdd.fragment.overview;
3 import java.io.FileNotFoundException;
4 import java.io.IOException;
5 import java.net.MalformedURLException;
6 import java.net.URISyntaxException;
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;
17 import org.apache.http.client.ClientProtocolException;
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;
34 import com.fasterxml.jackson.core.JsonParseException;
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;
49 public class WeatherInformationOverviewFragment extends ListFragment implements GetWeather {
50 private boolean mIsFahrenheit;
51 private String mDayForecast;
52 private WeatherServicePersistenceFile mWeatherServicePersistenceFile;
55 public void onCreate(final Bundle savedInstanceState) {
56 super.onCreate(savedInstanceState);
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, "");
64 this.mWeatherServicePersistenceFile = new WeatherServicePersistenceFile(this.getActivity());
65 this.mWeatherServicePersistenceFile.removeForecastWeatherData();
69 public void onActivityCreated(final Bundle savedInstanceState) {
70 super.onActivityCreated(savedInstanceState);
72 final ListView listWeatherView = this.getListView();
73 listWeatherView.setChoiceMode(ListView.CHOICE_MODE_NONE);
75 if (savedInstanceState != null) {
77 final ForecastWeatherData forecastWeatherData = (ForecastWeatherData) savedInstanceState
78 .getSerializable("ForecastWeatherData");
80 if (forecastWeatherData != null) {
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");
92 this.setHasOptionsMenu(false);
94 final WeatherOverviewAdapter adapter = new WeatherOverviewAdapter(
95 this.getActivity(), R.layout.weather_main_entry_list);
98 this.setEmptyText("Press download to receive weather information");
100 this.setListAdapter(adapter);
101 this.setListShown(true);
102 this.setListShownNoAnimation(true);
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) {
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);
118 fragment.getWeatherByDay((int) id);
123 public void onSaveInstanceState(final Bundle savedInstanceState) {
126 final ForecastWeatherData forecastWeatherData = this.mWeatherServicePersistenceFile
127 .getForecastWeatherData();
129 if (forecastWeatherData != null) {
130 savedInstanceState.putSerializable("ForecastWeatherData", forecastWeatherData);
133 super.onSaveInstanceState(savedInstanceState);
137 public void getRemoteWeatherInformation() {
139 final GeocodingData geocodingData = this.mWeatherServicePersistenceFile.getGeocodingData();
141 if (geocodingData != null) {
142 final IJPOSWeatherParser JPOSWeatherParser = new JPOSWeatherParser();
143 final WeatherServiceParser weatherService = new WeatherServiceParser(
145 final AndroidHttpClient httpClient = AndroidHttpClient
146 .newInstance("Android Weather Information Agent");
147 final CustomHTTPClient HTTPweatherClient = new CustomHTTPClient(
150 final ForecastWeatherTask weatherTask = new ForecastWeatherTask(HTTPweatherClient,
154 weatherTask.execute(geocodingData);
159 public void getWeatherByDay(final int chosenDay) {
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);
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";
177 final Calendar calendar = Calendar.getInstance();
178 for (final de.example.exampletdd.model.forecastweather.List forecast : forecastWeatherData
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);
187 Double maxTemp = null;
188 if (forecast.getTemp().getMax() != null) {
189 maxTemp = (Double) forecast.getTemp().getMax();
190 maxTemp = maxTemp - tempUnits;
193 Double minTemp = null;
194 if (forecast.getTemp().getMin() != null) {
195 minTemp = (Double) forecast.getTemp().getMin();
196 minTemp = minTemp - tempUnits;
199 if ((maxTemp != null) && (minTemp != null)) {
200 entries.add(new WeatherOverviewEntry(dayText, tempFormatter.format(maxTemp)
201 + symbol, tempFormatter.format(minTemp) + symbol, picture));
205 this.setListAdapter(null);
206 adapter.addAll(entries);
207 this.setListAdapter(adapter);
211 public void onResume() {
214 final SharedPreferences sharedPreferences = PreferenceManager
215 .getDefaultSharedPreferences(this.getActivity());
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;
226 this.mIsFahrenheit = true;
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, "");
235 // 3. Update forecast weather data on display.
236 final ForecastWeatherData forecastWeatherData = this.mWeatherServicePersistenceFile
237 .getForecastWeatherData();
238 if (forecastWeatherData != null) {
239 this.updateForecastWeatherData(forecastWeatherData);
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;
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));
261 protected void onPreExecute() {
262 this.newFragment.show(WeatherInformationOverviewFragment.this.getActivity()
263 .getFragmentManager(), "progressDialog");
267 protected ForecastWeatherData doInBackground(final Object... params) {
268 ForecastWeatherData forecastWeatherData = null;
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);
284 this.weatherHTTPClient.close();
287 return forecastWeatherData;
291 protected void onPostExecute(final ForecastWeatherData weatherData) {
292 this.weatherHTTPClient.close();
294 this.newFragment.dismiss();
296 if (weatherData != null) {
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");
306 final DialogFragment newFragment = ErrorDialogFragment
307 .newInstance(R.string.error_dialog_generic_error);
308 newFragment.show(WeatherInformationOverviewFragment.this.getFragmentManager(), "errorDialog");
313 protected void onCancelled(final ForecastWeatherData weatherData) {
314 this.weatherHTTPClient.close();
316 final DialogFragment newFragment = ErrorDialogFragment
317 .newInstance(R.string.error_dialog_connection_tiemout);
318 newFragment.show(WeatherInformationOverviewFragment.this.getFragmentManager(), "errorDialog");
321 private ForecastWeatherData doInBackgroundThrowable(final Object... params)
322 throws ClientProtocolException, MalformedURLException,
323 URISyntaxException, JsonParseException, IOException {
324 // final SharedPreferences sharedPreferences = PreferenceManager
325 // .getDefaultSharedPreferences(WeatherInformationOverviewFragment.this
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, "");
336 final GeocodingData geocodingData = (GeocodingData) params[0];
339 final String APIVersion = WeatherInformationOverviewFragment.this.getResources()
340 .getString(R.string.api_version);
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);
350 return forecastWeatherData;
353 private void onPostExecuteThrowable(final ForecastWeatherData forecastWeatherData)
354 throws FileNotFoundException, IOException {
355 WeatherInformationOverviewFragment.this.mWeatherServicePersistenceFile
356 .storeForecastWeatherData(forecastWeatherData);
358 WeatherInformationOverviewFragment.this.updateForecastWeatherData(forecastWeatherData);