1 package de.example.exampletdd.fragment.current;
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.Calendar;
11 import java.util.Date;
12 import java.util.Locale;
14 import org.apache.http.client.ClientProtocolException;
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;
37 import com.fasterxml.jackson.core.JsonParseException;
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;
50 public class CurrentFragment extends Fragment {
51 private static final String TAG = "CurrentFragment";
52 private BroadcastReceiver mReceiver;
55 public void onCreate(final Bundle savedInstanceState) {
56 super.onCreate(savedInstanceState);
60 public View onCreateView(LayoutInflater inflater, ViewGroup container,
61 Bundle savedInstanceState) {
63 // Inflate the layout for this fragment
64 return inflater.inflate(R.layout.weather_current_fragment, container, false);
68 public void onActivityCreated(final Bundle savedInstanceState) {
69 super.onActivityCreated(savedInstanceState);
71 if (savedInstanceState != null) {
73 final Current current = (Current) savedInstanceState.getSerializable("Current");
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);
83 this.setHasOptionsMenu(false);
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);
91 public void onResume() {
95 this.mReceiver = new BroadcastReceiver() {
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");
103 if (currentRemote != null) {
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();
111 if (current == null || !CurrentFragment.this.isDataFresh(weatherLocation.getLastCurrentUIUpdate())) {
113 CurrentFragment.this.updateUI(currentRemote);
115 // 3. Update current data.
116 store.saveCurrent(currentRemote);
118 // 4. Update location data.
119 weatherLocation.setLastCurrentUIUpdate(new Date());
120 query.updateDataBase(weatherLocation);
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);
134 final IntentFilter filter = new IntentFilter();
135 filter.addAction("de.example.exampletdd.UPDATECURRENT");
136 LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext())
137 .registerReceiver(this.mReceiver, filter);
140 this.getActivity().findViewById(R.id.weather_current_data_container).setVisibility(View.GONE);
142 final DatabaseQueries query = new DatabaseQueries(this.getActivity().getApplicationContext());
143 final WeatherLocation weatherLocation = query.queryDataBase();
144 if (weatherLocation == null) {
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);
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);
163 final PermanentStorage store = new PermanentStorage(this.getActivity().getApplicationContext());
164 final Current current = store.getCurrent();
166 if (current != null && this.isDataFresh(weatherLocation.getLastCurrentUIUpdate())) {
167 this.updateUI(current);
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()));
178 task.execute(weatherLocation.getLatitude(), weatherLocation.getLongitude());
183 public void onSaveInstanceState(final Bundle savedInstanceState) {
186 final PermanentStorage store = new PermanentStorage(this.getActivity().getApplicationContext());
187 final Current current = store.getCurrent();
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);
195 super.onSaveInstanceState(savedInstanceState);
199 public void onPause() {
200 LocalBroadcastManager.getInstance(this.getActivity().getApplicationContext()).unregisterReceiver(this.mReceiver);
205 private interface UnitsConversor {
207 public double doConversion(final double value);
210 private void updateUI(final Current current) {
212 final SharedPreferences sharedPreferences = PreferenceManager
213 .getDefaultSharedPreferences(this.getActivity().getApplicationContext());
215 // TODO: repeating the same code in Overview, Specific and Current!!!
216 // 1. Update units of measurement.
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(){
229 public double doConversion(final double value) {
230 return value - 273.15;
234 } else if (unitsPreferenceValue.equals(values[1])) {
235 tempSymbol = values[1];
236 tempUnitsConversor = new UnitsConversor(){
239 public double doConversion(final double value) {
240 return (value * 1.8) - 459.67;
245 tempSymbol = values[2];
246 tempUnitsConversor = new UnitsConversor(){
249 public double doConversion(final double value) {
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(){
268 public double doConversion(double value) {
273 windSymbol = values[1];
274 windUnitsConversor = new UnitsConversor(){
277 public double doConversion(double value) {
278 return value * 2.237;
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(){
295 public double doConversion(double value) {
300 pressureSymbol = values[1];
301 pressureUnitsConversor = new UnitsConversor(){
304 public double doConversion(double value) {
305 return value / 113.25d;
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);
317 // 3. Prepare data for UI.
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;
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;
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());
338 picture = BitmapFactory.decodeResource(this.getResources(),
339 R.drawable.weather_severe_alert);
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();
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
413 final TextView descriptionView = (TextView) getActivity().findViewById(R.id.weather_current_description);
414 descriptionView.setText(description);
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));
420 ((TextView) getActivity().findViewById(R.id.weather_current_pressure_value)).setText(pressureValue);
421 ((TextView) getActivity().findViewById(R.id.weather_current_pressure_units)).setText(pressureSymbol);
423 ((TextView) getActivity().findViewById(R.id.weather_current_wind_value)).setText(windValue);
424 ((TextView) getActivity().findViewById(R.id.weather_current_wind_units)).setText(windSymbol);
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));
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));
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));
438 ((TextView) getActivity().findViewById(R.id.weather_current_feelslike_value)).setText(feelsLike);
439 ((TextView) getActivity().findViewById(R.id.weather_current_feelslike_units)).setText(tempSymbol);
441 ((TextView) getActivity().findViewById(R.id.weather_current_sunrise_value)).setText(sunRiseTime);
443 ((TextView) getActivity().findViewById(R.id.weather_current_sunset_value)).setText(sunSetTime);
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);
450 private boolean isDataFresh(final Date lastUpdate) {
451 if (lastUpdate == null) {
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(
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)) {
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;
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;
483 protected Current doInBackground(final Object... params) {
484 final double latitude = (Double) params[0];
485 final double longitude = (Double) params[1];
487 Current current = null;
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);
508 private Current doInBackgroundThrowable(final double latitude, final double longitude)
509 throws URISyntaxException, ClientProtocolException, JsonParseException, IOException {
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));
517 return weatherService.retrieveCurrentFromJPOS(jsonData);
521 protected void onPostExecute(final Current current) {
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);