1 package de.example.exampletdd.fragment.overview;
3 import java.io.IOException;
4 import java.net.MalformedURLException;
5 import java.net.URISyntaxException;
7 import java.text.DecimalFormat;
8 import java.text.NumberFormat;
9 import java.text.SimpleDateFormat;
10 import java.util.ArrayList;
11 import java.util.Calendar;
12 import java.util.Date;
13 import java.util.List;
14 import java.util.Locale;
16 import org.apache.http.client.ClientProtocolException;
18 import android.content.BroadcastReceiver;
19 import android.content.ComponentName;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.IntentFilter;
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.support.v4.app.ListFragment;
31 import android.support.v4.content.LocalBroadcastManager;
32 import android.util.Log;
33 import android.view.View;
34 import android.widget.ListView;
36 import com.fasterxml.jackson.core.JsonParseException;
38 import de.example.exampletdd.R;
39 import de.example.exampletdd.fragment.specific.SpecificFragment;
40 import de.example.exampletdd.httpclient.CustomHTTPClient;
41 import de.example.exampletdd.model.DatabaseQueries;
42 import de.example.exampletdd.model.WeatherLocation;
43 import de.example.exampletdd.model.forecastweather.Forecast;
44 import de.example.exampletdd.parser.JPOSWeatherParser;
45 import de.example.exampletdd.service.IconsList;
46 import de.example.exampletdd.service.PermanentStorage;
47 import de.example.exampletdd.service.ServiceParser;
49 public class OverviewFragment extends ListFragment {
50 private static final String TAG = "OverviewFragment";
51 private BroadcastReceiver mReceiver;
54 public void onCreate(final Bundle savedInstanceState) {
55 super.onCreate(savedInstanceState);
59 public void onActivityCreated(final Bundle savedInstanceState) {
60 super.onActivityCreated(savedInstanceState);
62 final ListView listWeatherView = this.getListView();
63 listWeatherView.setChoiceMode(ListView.CHOICE_MODE_NONE);
65 if (savedInstanceState != null) {
67 final Forecast forecast = (Forecast) savedInstanceState.getSerializable("Forecast");
69 // TODO: Could it be better to store in global forecast data even if it is null value?
70 // So, perhaps do not check for null value and always store in global variable.
71 if (forecast != null) {
72 final PermanentStorage store = new PermanentStorage(this.getActivity().getApplicationContext());
73 store.saveForecast(forecast);
77 this.setHasOptionsMenu(false);
79 this.setEmptyText(this.getString(R.string.text_field_remote_error));
80 this.setListShownNoAnimation(false);
84 public void onResume() {
87 this.mReceiver = new BroadcastReceiver() {
90 public void onReceive(final Context context, final Intent intent) {
91 final String action = intent.getAction();
92 if (action.equals("de.example.exampletdd.UPDATEFORECAST")) {
93 final Forecast forecastRemote = (Forecast) intent.getSerializableExtra("forecast");
95 if (forecastRemote != null) {
97 // 1. Check conditions. They must be the same as the ones that triggered the AsyncTask.
98 final DatabaseQueries query = new DatabaseQueries(context.getApplicationContext());
99 final WeatherLocation weatherLocation = query.queryDataBase();
100 final PermanentStorage store = new PermanentStorage(context.getApplicationContext());
101 final Forecast forecast = store.getForecast();
103 if (forecast == null || !OverviewFragment.this.isDataFresh(weatherLocation.getLastForecastUIUpdate())) {
105 OverviewFragment.this.updateUI(forecastRemote);
108 store.saveForecast(forecastRemote);
109 weatherLocation.setLastForecastUIUpdate(new Date());
110 query.updateDataBase(weatherLocation);
113 OverviewFragment.this.setListShownNoAnimation(true);
117 // Empty list and show error message (see setEmptyText in onCreate)
118 OverviewFragment.this.setListAdapter(null);
119 OverviewFragment.this.setListShownNoAnimation(true);
126 final IntentFilter filter = new IntentFilter();
127 filter.addAction("de.example.exampletdd.UPDATEFORECAST");
128 LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext())
129 .registerReceiver(this.mReceiver, filter);
131 final DatabaseQueries query = new DatabaseQueries(this.getActivity().getApplicationContext());
132 final WeatherLocation weatherLocation = query.queryDataBase();
133 if (weatherLocation == null) {
135 // Empty list and show error message (see setEmptyText in onCreate)
136 this.setListAdapter(null);
137 this.setListShownNoAnimation(true);
141 final PermanentStorage store = new PermanentStorage(this.getActivity().getApplicationContext());
142 final Forecast forecast = store.getForecast();
144 // TODO: store forecast data in permanent storage and check here if there is data in permanent storage
145 if (forecast != null && this.isDataFresh(weatherLocation.getLastForecastUIUpdate())) {
146 this.updateUI(forecast);
148 // Load remote data (aynchronous)
149 // Gets the data from the web.
150 this.setListShownNoAnimation(false);
151 final OverviewTask task = new OverviewTask(
152 this.getActivity().getApplicationContext(),
153 new CustomHTTPClient(AndroidHttpClient.newInstance("Android 4.3 WeatherInformation Agent")),
154 new ServiceParser(new JPOSWeatherParser()));
156 task.execute(weatherLocation.getLatitude(), weatherLocation.getLongitude());
161 public void onSaveInstanceState(final Bundle savedInstanceState) {
164 final PermanentStorage store = new PermanentStorage(this.getActivity().getApplicationContext());
165 final Forecast forecast = store.getForecast();
167 // TODO: Could it be better to save forecast data even if it is null value?
168 // So, perhaps do not check for null value.
169 if (forecast != null) {
170 savedInstanceState.putSerializable("Forecast", forecast);
173 super.onSaveInstanceState(savedInstanceState);
177 public void onPause() {
178 LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext()).unregisterReceiver(this.mReceiver);
184 public void onListItemClick(final ListView l, final View v, final int position, final long id) {
185 final SpecificFragment fragment = (SpecificFragment) this
186 .getFragmentManager().findFragmentById(R.id.weather_specific_fragment);
187 if (fragment == null) {
189 final Intent intent = new Intent("de.example.exampletdd.WEATHERINFO")
190 .setComponent(new ComponentName("de.example.exampletdd",
191 "de.example.exampletdd.SpecificActivity"));
192 intent.putExtra("CHOSEN_DAY", (int) id);
193 OverviewFragment.this.getActivity().startActivity(intent);
196 fragment.updateUIByChosenDay((int) id);
200 private interface UnitsConversor {
202 public double doConversion(final double value);
205 private void updateUI(final Forecast forecastWeatherData) {
207 final SharedPreferences sharedPreferences = PreferenceManager
208 .getDefaultSharedPreferences(this.getActivity().getApplicationContext());
210 // TODO: repeating the same code in Overview, Specific and Current!!!
211 // 1. Update units of measurement.
213 UnitsConversor unitsConversor;
214 String keyPreference = this.getResources().getString(
215 R.string.weather_preferences_temperature_key);
216 final String[] values = this.getResources().getStringArray(R.array.weather_preferences_temperature);
217 final String unitsPreferenceValue = sharedPreferences.getString(
218 keyPreference, this.getString(R.string.weather_preferences_temperature_celsius));
219 if (unitsPreferenceValue.equals(values[0])) {
221 unitsConversor = new UnitsConversor(){
224 public double doConversion(final double value) {
225 return value - 273.15;
229 } else if (unitsPreferenceValue.equals(values[1])) {
231 unitsConversor = new UnitsConversor(){
234 public double doConversion(final double value) {
235 return (value * 1.8) - 459.67;
241 unitsConversor = new UnitsConversor(){
244 public double doConversion(final double value) {
252 // 2. Update number day forecast.
253 keyPreference = this.getResources().getString(R.string.weather_preferences_day_forecast_key);
254 final String dayForecast = sharedPreferences.getString(keyPreference, "5");
255 final int mDayForecast = Integer.valueOf(dayForecast);
259 final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
260 tempFormatter.applyPattern("#####.##");
261 final SimpleDateFormat dayNameFormatter = new SimpleDateFormat("EEE", Locale.US);
262 final SimpleDateFormat monthAndDayNumberormatter = new SimpleDateFormat("MMM d", Locale.US);
265 // 4. Prepare data for UI.
266 final List<OverviewEntry> entries = new ArrayList<OverviewEntry>();
267 final OverviewAdapter adapter = new OverviewAdapter(this.getActivity(),
268 R.layout.weather_main_entry_list);
269 final Calendar calendar = Calendar.getInstance();
270 int count = mDayForecast;
271 for (final de.example.exampletdd.model.forecastweather.List forecast : forecastWeatherData
276 if ((forecast.getWeather().size() > 0) &&
277 (forecast.getWeather().get(0).getIcon() != null) &&
278 (IconsList.getIcon(forecast.getWeather().get(0).getIcon()) != null)) {
279 final String icon = forecast.getWeather().get(0).getIcon();
280 picture = BitmapFactory.decodeResource(this.getResources(), IconsList.getIcon(icon)
281 .getResourceDrawable());
283 picture = BitmapFactory.decodeResource(this.getResources(),
284 R.drawable.weather_severe_alert);
287 final Long forecastUNIXDate = (Long) forecast.getDt();
288 calendar.setTimeInMillis(forecastUNIXDate * 1000L);
289 final Date dayTime = calendar.getTime();
290 final String dayTextName = dayNameFormatter.format(dayTime);
291 final String monthAndDayNumberText = monthAndDayNumberormatter.format(dayTime);
293 Double maxTemp = null;
294 if (forecast.getTemp().getMax() != null) {
295 maxTemp = (Double) forecast.getTemp().getMax();
296 maxTemp = unitsConversor.doConversion(maxTemp);
299 Double minTemp = null;
300 if (forecast.getTemp().getMin() != null) {
301 minTemp = (Double) forecast.getTemp().getMin();
302 minTemp = unitsConversor.doConversion(minTemp);
305 if ((maxTemp != null) && (minTemp != null)) {
306 entries.add(new OverviewEntry(dayTextName, monthAndDayNumberText,
307 tempFormatter.format(maxTemp) + symbol, tempFormatter.format(minTemp) + symbol,
319 adapter.addAll(entries);
320 this.setListAdapter(adapter);
323 private boolean isDataFresh(final Date lastUpdate) {
324 if (lastUpdate == null) {
328 final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(
329 this.getActivity().getApplicationContext());
330 final String keyPreference = this.getString(R.string.weather_preferences_refresh_interval_key);
331 final String refresh = sharedPreferences.getString(
333 this.getResources().getStringArray(R.array.weather_preferences_refresh_interval)[0]);
334 final Date currentTime = new Date();
335 if (((currentTime.getTime() - lastUpdate.getTime())) < Long.valueOf(refresh)) {
342 private class OverviewTask extends AsyncTask<Object, Void, Forecast> {
343 // Store the context passed to the AsyncTask when the system instantiates it.
344 private final Context localContext;
345 private final CustomHTTPClient HTTPClient;
346 private final ServiceParser weatherService;
348 public OverviewTask(final Context context, final CustomHTTPClient HTTPClient,
349 final ServiceParser weatherService) {
350 this.localContext = context;
351 this.HTTPClient = HTTPClient;
352 this.weatherService = weatherService;
356 protected Forecast doInBackground(final Object... params) {
357 final double latitude = (Double) params[0];
358 final double longitude = (Double) params[1];
360 Forecast forecast = null;
363 forecast = this.doInBackgroundThrowable(latitude, longitude);
364 } catch (final JsonParseException e) {
365 Log.e(TAG, "OverviewTask doInBackground exception: ", e);
366 } catch (final ClientProtocolException e) {
367 Log.e(TAG, "OverviewTask doInBackground exception: ", e);
368 } catch (final MalformedURLException e) {
369 Log.e(TAG, "OverviewTask doInBackground exception: ", e);
370 } catch (final URISyntaxException e) {
371 Log.e(TAG, "OverviewTask doInBackground exception: ", e);
372 } catch (final IOException e) {
373 // logger infrastructure swallows UnknownHostException :/
374 Log.e(TAG, "OverviewTask doInBackground exception: " + e.getMessage(), e);
382 private Forecast doInBackgroundThrowable(final double latitude, final double longitude)
383 throws URISyntaxException, ClientProtocolException, JsonParseException, IOException {
385 final String APIVersion = localContext.getResources().getString(R.string.api_version);
386 final String urlAPI = localContext.getResources().getString(R.string.uri_api_weather_forecast);
387 // TODO: number as resource
388 final String url = weatherService.createURIAPIForecast(urlAPI, APIVersion, latitude, longitude, "14");
389 final String urlWithoutCache = url.concat("&time=" + System.currentTimeMillis());
390 final String jsonData = HTTPClient.retrieveDataAsString(new URL(urlWithoutCache));
392 return weatherService.retrieveForecastFromJPOS(jsonData);
396 protected void onPostExecute(final Forecast forecast) {
398 // Call updateUI on the UI thread.
399 final Intent forecastData = new Intent("de.example.exampletdd.UPDATEFORECAST");
400 forecastData.putExtra("forecast", forecast);
401 LocalBroadcastManager.getInstance(this.localContext).sendBroadcastSync(forecastData);