dbec00e69408aa74d4afe92020780a6083443c9d
[JavaForFun] /
1 package de.example.exampletdd.fragment.current;
2
3 import java.io.IOException;
4 import java.net.MalformedURLException;
5 import java.net.URISyntaxException;
6 import java.net.URL;
7 import java.text.DecimalFormat;
8 import java.text.NumberFormat;
9 import java.text.SimpleDateFormat;
10 import java.util.Calendar;
11 import java.util.Date;
12 import java.util.Locale;
13
14 import org.apache.http.client.ClientProtocolException;
15
16 import android.content.BroadcastReceiver;
17 import android.content.Context;
18 import android.content.Intent;
19 import android.content.IntentFilter;
20 import android.content.SharedPreferences;
21 import android.graphics.Bitmap;
22 import android.graphics.BitmapFactory;
23 import android.net.http.AndroidHttpClient;
24 import android.os.AsyncTask;
25 import android.os.Bundle;
26 import android.preference.PreferenceManager;
27 import android.support.v4.app.Fragment;
28 import android.support.v4.content.LocalBroadcastManager;
29 import android.util.Log;
30 import android.view.LayoutInflater;
31 import android.view.View;
32 import android.view.ViewGroup;
33 import android.widget.ImageView;
34 import android.widget.ProgressBar;
35 import android.widget.TextView;
36
37 import com.fasterxml.jackson.core.JsonParseException;
38
39 import de.example.exampletdd.R;
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.currentweather.Current;
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;
48 import de.example.exampletdd.widget.WidgetProvider;
49
50 public class CurrentFragment extends Fragment {
51     private static final String TAG = "CurrentFragment";
52     private BroadcastReceiver mReceiver;
53
54     @Override
55     public void onCreate(final Bundle savedInstanceState) {
56         super.onCreate(savedInstanceState);
57     }
58
59     @Override
60     public View onCreateView(LayoutInflater inflater, ViewGroup container,
61                              Bundle savedInstanceState) {
62     
63         // Inflate the layout for this fragment
64         return inflater.inflate(R.layout.weather_current_fragment, container, false);
65     }
66     
67     @Override
68     public void onActivityCreated(final Bundle savedInstanceState) {
69         super.onActivityCreated(savedInstanceState);
70
71         if (savedInstanceState != null) {
72                 // Restore UI state
73             final Current current = (Current) savedInstanceState.getSerializable("Current");
74
75             // TODO: Could it be better to store in global forecast data even if it is null value?
76             //       So, perhaps do not check for null value and always store in global variable.
77             if (current != null) {
78                 final PermanentStorage store = new PermanentStorage(this.getActivity().getApplicationContext());
79                 store.saveCurrent(current);
80             }
81         }     
82         
83         this.setHasOptionsMenu(false);
84
85         this.getActivity().findViewById(R.id.weather_current_data_container).setVisibility(View.GONE);
86         this.getActivity().findViewById(R.id.weather_current_progressbar).setVisibility(View.VISIBLE);
87         this.getActivity().findViewById(R.id.weather_current_error_message).setVisibility(View.GONE);   
88     }
89
90     @Override
91     public void onResume() {
92         super.onResume();
93
94
95         this.mReceiver = new BroadcastReceiver() {
96
97                         @Override
98                         public void onReceive(final Context context, final Intent intent) {
99                                 final String action = intent.getAction();
100                                 if (action.equals("de.example.exampletdd.UPDATECURRENT")) {
101                                         final Current currentRemote = (Current) intent.getSerializableExtra("current");
102
103                                         if (currentRemote != null) {
104
105                                                 // 1. Check conditions. They must be the same as the ones that triggered the AsyncTask.
106                                                 final DatabaseQueries query = new DatabaseQueries(context.getApplicationContext());
107                                     final WeatherLocation weatherLocation = query.queryDataBase();
108                                     final PermanentStorage store = new PermanentStorage(context.getApplicationContext());
109                                     final Current current = store.getCurrent();
110
111                                     if (current == null || !CurrentFragment.this.isDataFresh(weatherLocation.getLastCurrentUIUpdate())) {
112                                         // 2. Update UI.
113                                         CurrentFragment.this.updateUI(currentRemote);
114
115                                         // 3. Update current data.
116                                                         store.saveCurrent(currentRemote);
117
118                             // 4. Update location data.
119                             weatherLocation.setLastCurrentUIUpdate(new Date());
120                             query.updateDataBase(weatherLocation);
121                                     }
122
123                                         } else {
124                                                 // Empty UI and show error message
125                                                 CurrentFragment.this.getActivity().findViewById(R.id.weather_current_data_container).setVisibility(View.GONE);
126                                                 CurrentFragment.this.getActivity().findViewById(R.id.weather_current_progressbar).setVisibility(View.GONE);
127                                                 CurrentFragment.this.getActivity().findViewById(R.id.weather_current_error_message).setVisibility(View.VISIBLE);
128                                         }
129                                 }
130                         }
131         };
132
133         // Register receiver
134         final IntentFilter filter = new IntentFilter();
135         filter.addAction("de.example.exampletdd.UPDATECURRENT");
136         LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext())
137                                                         .registerReceiver(this.mReceiver, filter);
138
139         // Empty UI
140         this.getActivity().findViewById(R.id.weather_current_data_container).setVisibility(View.GONE);
141         
142         final DatabaseQueries query = new DatabaseQueries(this.getActivity().getApplicationContext());
143         final WeatherLocation weatherLocation = query.queryDataBase();
144         if (weatherLocation == null) {
145             // Nothing to do.
146                 // Show error message
147                 final ProgressBar progress = (ProgressBar) getActivity().findViewById(R.id.weather_current_progressbar);
148                 progress.setVisibility(View.GONE);
149                         final TextView errorMessage = (TextView) getActivity().findViewById(R.id.weather_current_error_message);
150                 errorMessage.setVisibility(View.VISIBLE);
151             return;
152         }
153
154         // If is new location update widgets.
155         if (weatherLocation.getIsNew()) {
156             WidgetProvider.refreshAllAppWidgets(this.getActivity().getApplicationContext());
157             // Update location data.
158             weatherLocation.setIsNew(false);
159             query.updateDataBase(weatherLocation);
160         }
161
162
163         final PermanentStorage store = new PermanentStorage(this.getActivity().getApplicationContext());
164         final Current current = store.getCurrent();
165
166         if (current != null && this.isDataFresh(weatherLocation.getLastCurrentUIUpdate())) {
167             this.updateUI(current);
168         } else {
169             // Load remote data (aynchronous)
170             // Gets the data from the web.
171                 this.getActivity().findViewById(R.id.weather_current_progressbar).setVisibility(View.VISIBLE);
172                 this.getActivity().findViewById(R.id.weather_current_error_message).setVisibility(View.GONE);
173             final CurrentTask task = new CurrentTask(
174                         this.getActivity().getApplicationContext(),
175                     new CustomHTTPClient(AndroidHttpClient.newInstance("Android 4.3 WeatherInformation Agent")),
176                     new ServiceParser(new JPOSWeatherParser()));
177
178             task.execute(weatherLocation.getLatitude(), weatherLocation.getLongitude());
179         }
180     }
181
182     @Override
183     public void onSaveInstanceState(final Bundle savedInstanceState) {
184
185         // Save UI state
186         final PermanentStorage store = new PermanentStorage(this.getActivity().getApplicationContext());
187         final Current current = store.getCurrent();
188
189         // TODO: Could it be better to save current data even if it is null value?
190         //       So, perhaps do not check for null value.
191         if (current != null) {
192             savedInstanceState.putSerializable("Current", current);
193         }
194
195         super.onSaveInstanceState(savedInstanceState);
196     }
197
198     @Override
199     public void onPause() {
200         LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext()).unregisterReceiver(this.mReceiver);
201
202         super.onPause();
203     }
204
205     private interface UnitsConversor {
206         
207         public double doConversion(final double value);
208     }
209
210     private void updateUI(final Current current) {
211         
212         final SharedPreferences sharedPreferences = PreferenceManager
213                 .getDefaultSharedPreferences(this.getActivity().getApplicationContext());
214
215         // TODO: repeating the same code in Overview, Specific and Current!!!
216         // 1. Update units of measurement.
217         // 1.1 Temperature
218         String tempSymbol;
219         UnitsConversor tempUnitsConversor;
220         String keyPreference = this.getResources().getString(R.string.weather_preferences_temperature_key);
221         String[] values = this.getResources().getStringArray(R.array.weather_preferences_temperature);
222         String unitsPreferenceValue = sharedPreferences.getString(
223                 keyPreference, this.getString(R.string.weather_preferences_temperature_celsius));
224         if (unitsPreferenceValue.equals(values[0])) {
225                 tempSymbol = values[0];
226                 tempUnitsConversor = new UnitsConversor(){
227
228                                 @Override
229                                 public double doConversion(final double value) {
230                                         return value - 273.15;
231                                 }
232                         
233                 };
234         } else if (unitsPreferenceValue.equals(values[1])) {
235                 tempSymbol = values[1];
236                 tempUnitsConversor = new UnitsConversor(){
237
238                                 @Override
239                                 public double doConversion(final double value) {
240                                         return (value * 1.8) - 459.67;
241                                 }
242                         
243                 };
244         } else {
245                 tempSymbol = values[2];
246                 tempUnitsConversor = new UnitsConversor(){
247
248                                 @Override
249                                 public double doConversion(final double value) {
250                                         return value;
251                                 }
252                         
253                 };
254         }
255
256         // 1.2 Wind
257         String windSymbol;
258         UnitsConversor windUnitsConversor;
259         keyPreference = this.getResources().getString(R.string.weather_preferences_wind_key);
260         values = this.getResources().getStringArray(R.array.weather_preferences_wind);
261         unitsPreferenceValue = sharedPreferences.getString(
262                 keyPreference, this.getString(R.string.weather_preferences_wind_meters));
263         if (unitsPreferenceValue.equals(values[0])) {
264                 windSymbol = values[0];
265                 windUnitsConversor = new UnitsConversor(){
266
267                         @Override
268                         public double doConversion(double value) {
269                                 return value;
270                         }       
271                 };
272         } else {
273                 windSymbol = values[1];
274                 windUnitsConversor = new UnitsConversor(){
275
276                         @Override
277                         public double doConversion(double value) {
278                                 return value * 2.237;
279                         }       
280                 };
281         }
282
283         // 1.3 Pressure
284         String pressureSymbol;
285         UnitsConversor pressureUnitsConversor;
286         keyPreference = this.getResources().getString(R.string.weather_preferences_pressure_key);
287         values = this.getResources().getStringArray(R.array.weather_preferences_pressure);
288         unitsPreferenceValue = sharedPreferences.getString(
289                 keyPreference, this.getString(R.string.weather_preferences_pressure_pascal));
290         if (unitsPreferenceValue.equals(values[0])) {
291                 pressureSymbol = values[0];
292                 pressureUnitsConversor = new UnitsConversor(){
293
294                         @Override
295                         public double doConversion(double value) {
296                                 return value;
297                         }       
298                 };
299         } else {
300                 pressureSymbol = values[1];
301                 pressureUnitsConversor = new UnitsConversor(){
302
303                         @Override
304                         public double doConversion(double value) {
305                                 return value / 113.25d;
306                         }       
307                 };
308         }
309
310
311         // 2. Formatters
312         final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
313         tempFormatter.applyPattern("#####.#####");
314         final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss", Locale.US);
315
316         
317         // 3. Prepare data for UI.
318         String tempMax = "";
319         if (current.getMain().getTemp_max() != null) {
320             double conversion = (Double) current.getMain().getTemp_max();
321             conversion = tempUnitsConversor.doConversion(conversion);
322             tempMax = tempFormatter.format(conversion) + tempSymbol;
323         }
324         String tempMin = "";
325         if (current.getMain().getTemp_min() != null) {
326             double conversion = (Double) current.getMain().getTemp_min();
327             conversion = tempUnitsConversor.doConversion(conversion);
328             tempMin = tempFormatter.format(conversion) + tempSymbol;
329         }
330         Bitmap picture;
331         if ((current.getWeather().size() > 0)
332                 && (current.getWeather().get(0).getIcon() != null)
333                 && (IconsList.getIcon(current.getWeather().get(0).getIcon()) != null)) {
334             final String icon = current.getWeather().get(0).getIcon();
335             picture = BitmapFactory.decodeResource(this.getResources(), IconsList.getIcon(icon)
336                     .getResourceDrawable());
337         } else {
338             picture = BitmapFactory.decodeResource(this.getResources(),
339                     R.drawable.weather_severe_alert);
340         }
341
342         String description = this.getString(R.string.test_field_description_when_error);
343         if (current.getWeather().size() > 0) {
344             description = current.getWeather().get(0).getDescription();
345         }
346
347         String humidityValue = "";
348         if ((current.getMain() != null)
349                 && (current.getMain().getHumidity() != null)) {
350             final double conversion = (Double) current.getMain().getHumidity();
351             humidityValue = tempFormatter.format(conversion);
352         }
353         String pressureValue = "";
354         if ((current.getMain() != null)
355                 && (current.getMain().getPressure() != null)) {
356             double conversion = (Double) current.getMain().getPressure();
357             conversion = pressureUnitsConversor.doConversion(conversion);
358             pressureValue = tempFormatter.format(conversion);
359         }
360         String windValue = "";
361         if ((current.getWind() != null)
362                 && (current.getWind().getSpeed() != null)) {
363             double conversion = (Double) current.getWind().getSpeed();
364             conversion = windUnitsConversor.doConversion(conversion);
365             windValue = tempFormatter.format(conversion);
366         }
367         String rainValue = "";
368         if ((current.getRain() != null)
369                 && (current.getRain().get3h() != null)) {
370             final double conversion = (Double) current.getRain().get3h();
371             rainValue = tempFormatter.format(conversion);
372         }
373         String cloudsValue = "";
374         if ((current.getClouds() != null)
375                 && (current.getClouds().getAll() != null)) {
376             final double conversion = (Double) current.getClouds().getAll();
377             cloudsValue = tempFormatter.format(conversion);
378         }
379         String snowValue = "";
380         if ((current.getSnow() != null)
381                 && (current.getSnow().get3h() != null)) {
382             final double conversion = (Double) current.getSnow().get3h();
383             snowValue = tempFormatter.format(conversion);
384         }
385         String feelsLike = "";
386         if (current.getMain().getTemp() != null) {
387             double conversion = (Double) current.getMain().getTemp();
388             conversion = tempUnitsConversor.doConversion(conversion);
389             feelsLike = tempFormatter.format(conversion);
390         }
391         String sunRiseTime = "";
392         if (current.getSys().getSunrise() != null) {
393             final long unixTime = (Long) current.getSys().getSunrise();
394             final Date unixDate = new Date(unixTime * 1000L);
395             sunRiseTime = dateFormat.format(unixDate);
396         }
397         String sunSetTime = "";
398         if (current.getSys().getSunset() != null) {
399             final long unixTime = (Long) current.getSys().getSunset();
400             final Date unixDate = new Date(unixTime * 1000L);
401             sunSetTime = dateFormat.format(unixDate);
402         }
403
404
405         // 4. Update UI.
406         final TextView tempMaxView = (TextView) getActivity().findViewById(R.id.weather_current_temp_max);
407         tempMaxView.setText(tempMax);
408         final TextView tempMinView = (TextView) getActivity().findViewById(R.id.weather_current_temp_min);
409         tempMinView.setText(tempMin);
410         final ImageView pictureView = (ImageView) getActivity().findViewById(R.id.weather_current_picture);
411         pictureView.setImageBitmap(picture);    
412         
413         final TextView descriptionView = (TextView) getActivity().findViewById(R.id.weather_current_description);
414         descriptionView.setText(description);
415         
416         ((TextView) getActivity().findViewById(R.id.weather_current_humidity_value)).setText(humidityValue);
417         ((TextView) getActivity().findViewById(R.id.weather_current_humidity_units)).setText(
418                         this.getActivity().getApplicationContext().getString(R.string.text_units_percent));
419         
420         ((TextView) getActivity().findViewById(R.id.weather_current_pressure_value)).setText(pressureValue);
421         ((TextView) getActivity().findViewById(R.id.weather_current_pressure_units)).setText(pressureSymbol);
422         
423         ((TextView) getActivity().findViewById(R.id.weather_current_wind_value)).setText(windValue);
424         ((TextView) getActivity().findViewById(R.id.weather_current_wind_units)).setText(windSymbol);
425         
426         ((TextView) getActivity().findViewById(R.id.weather_current_rain_value)).setText(rainValue);
427         ((TextView) getActivity().findViewById(R.id.weather_current_rain_units)).setText(
428                         this.getActivity().getApplicationContext().getString(R.string.text_units_mm3h));
429         
430         ((TextView) getActivity().findViewById(R.id.weather_current_clouds_value)).setText(cloudsValue);
431         ((TextView) getActivity().findViewById(R.id.weather_current_clouds_units)).setText(
432                         this.getActivity().getApplicationContext().getString(R.string.text_units_percent));
433         
434         ((TextView) getActivity().findViewById(R.id.weather_current_snow_value)).setText(snowValue);
435         ((TextView) getActivity().findViewById(R.id.weather_current_snow_units)).setText(
436                         this.getActivity().getApplicationContext().getString(R.string.text_units_mm3h));
437         
438         ((TextView) getActivity().findViewById(R.id.weather_current_feelslike_value)).setText(feelsLike);
439         ((TextView) getActivity().findViewById(R.id.weather_current_feelslike_units)).setText(tempSymbol);
440         
441         ((TextView) getActivity().findViewById(R.id.weather_current_sunrise_value)).setText(sunRiseTime);
442
443         ((TextView) getActivity().findViewById(R.id.weather_current_sunset_value)).setText(sunSetTime);
444         
445         this.getActivity().findViewById(R.id.weather_current_data_container).setVisibility(View.VISIBLE);
446         this.getActivity().findViewById(R.id.weather_current_progressbar).setVisibility(View.GONE);
447         this.getActivity().findViewById(R.id.weather_current_error_message).setVisibility(View.GONE);       
448     }
449     
450     private boolean isDataFresh(final Date lastUpdate) {
451         if (lastUpdate == null) {
452                 return false;
453         }
454         
455         final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(
456                         this.getActivity().getApplicationContext());
457         final String keyPreference = this.getString(R.string.weather_preferences_refresh_interval_key);
458         final String refresh = sharedPreferences.getString(
459                         keyPreference,
460                         this.getResources().getStringArray(R.array.weather_preferences_refresh_interval)[0]);
461         final Date currentTime = new Date();
462         if (((currentTime.getTime() - lastUpdate.getTime())) < Long.valueOf(refresh)) {
463                 return true;
464         }
465         
466         return false;
467     }
468
469     private class CurrentTask extends AsyncTask<Object, Void, Current> {
470         // Store the context passed to the AsyncTask when the system instantiates it.
471         private final Context localContext;
472         final CustomHTTPClient HTTPClient;
473         final ServiceParser weatherService;
474
475         public CurrentTask(final Context context, final CustomHTTPClient HTTPClient,
476                         final ServiceParser weatherService) {
477                 this.localContext = context;
478             this.HTTPClient = HTTPClient;
479             this.weatherService = weatherService;
480         }
481
482         @Override
483         protected Current doInBackground(final Object... params) {
484                 final double latitude = (Double) params[0];
485             final double longitude = (Double) params[1];
486   
487             Current current = null;
488             try {
489                 current = this.doInBackgroundThrowable(latitude, longitude);
490             } catch (final JsonParseException e) {
491                 Log.e(TAG, "CurrentTask doInBackground exception: ", e);
492             } catch (final ClientProtocolException e) {
493                 Log.e(TAG, "CurrentTask doInBackground exception: ", e);
494             } catch (final MalformedURLException e) {
495                 Log.e(TAG, "CurrentTask doInBackground exception: ", e);
496             } catch (final URISyntaxException e) {
497                 Log.e(TAG, "CurrentTask doInBackground exception: ", e);
498             } catch (final IOException e) {
499                 // logger infrastructure swallows UnknownHostException :/
500                 Log.e(TAG, "CurrentTask doInBackground exception: " + e.getMessage(), e);
501             } finally {
502                 HTTPClient.close();
503             }
504
505             return current;
506         }
507
508         private Current doInBackgroundThrowable(final double latitude, final double longitude)
509                         throws URISyntaxException, ClientProtocolException, JsonParseException, IOException {
510
511                 final String APIVersion = localContext.getResources().getString(R.string.api_version);
512             final String urlAPI = localContext.getResources().getString(R.string.uri_api_weather_today);
513             final String url = weatherService.createURIAPICurrent(urlAPI, APIVersion, latitude, longitude);
514             final String urlWithoutCache = url.concat("&time=" + System.currentTimeMillis());
515             final String jsonData = HTTPClient.retrieveDataAsString(new URL(urlWithoutCache));
516
517             return weatherService.retrieveCurrentFromJPOS(jsonData);
518         }
519
520         @Override
521         protected void onPostExecute(final Current current) {
522
523             // Call updateUI on the UI thread.
524             final Intent currentData = new Intent("de.example.exampletdd.UPDATECURRENT");
525             currentData.putExtra("current", current);
526             LocalBroadcastManager.getInstance(this.localContext).sendBroadcastSync(currentData);
527         }
528     }
529 }