b53d4a67bc6f4801b7ae3d533659075e2b4ef904
[JavaForFun] /
1 package de.example.exampletdd.fragment.specific;
2
3 import java.io.FileNotFoundException;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.ObjectInputStream;
7 import java.io.ObjectOutputStream;
8 import java.io.OutputStream;
9 import java.io.StreamCorruptedException;
10 import java.text.DecimalFormat;
11 import java.text.NumberFormat;
12 import java.text.SimpleDateFormat;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Date;
16 import java.util.List;
17 import java.util.Locale;
18
19 import android.app.DialogFragment;
20 import android.app.Fragment;
21 import android.content.Context;
22 import android.content.SharedPreferences;
23 import android.graphics.Bitmap;
24 import android.graphics.BitmapFactory;
25 import android.os.Bundle;
26 import android.preference.PreferenceManager;
27 import android.util.Log;
28 import android.view.LayoutInflater;
29 import android.view.View;
30 import android.view.ViewGroup;
31 import android.widget.ImageView;
32 import android.widget.ListView;
33 import de.example.exampletdd.R;
34 import de.example.exampletdd.activityinterface.GetWeather;
35 import de.example.exampletdd.fragment.ErrorDialogFragment;
36 import de.example.exampletdd.model.WeatherData;
37
38 public class WeatherInformationSpecificDataFragment extends Fragment implements GetWeather {
39     private static final String WEATHER_DATA_FILE = "weatherdata.file";
40     private static final String TAG = "WeatherInformationDataFragment";
41     private boolean mIsFahrenheit;
42     private String mLanguage;
43
44     @Override
45     public void onCreate(final Bundle savedInstanceState) {
46         super.onCreate(savedInstanceState);
47
48         this.getActivity().deleteFile(WEATHER_DATA_FILE);
49
50         final SharedPreferences sharedPreferences = PreferenceManager
51                 .getDefaultSharedPreferences(this.getActivity());
52         final String keyPreference = this.getResources().getString(
53                 R.string.weather_preferences_language_key);
54         this.mLanguage = sharedPreferences.getString(
55                 keyPreference, "");
56     }
57
58     @Override
59     public View onCreateView(final LayoutInflater inflater,
60             final ViewGroup container, final Bundle savedInstanceState) {
61         final View rootView = inflater.inflate(R.layout.weather_data_list,
62                 container, false);
63
64         return rootView;
65     }
66
67     @Override
68     public void onActivityCreated(final Bundle savedInstanceState) {
69         super.onActivityCreated(savedInstanceState);
70
71         final ListView listWeatherView = (ListView) this.getActivity().findViewById(
72                 R.id.weather_data_list_view);
73
74         final WeatherSpecificDataAdapter adapter = new WeatherSpecificDataAdapter(this.getActivity(),
75                 R.layout.weather_data_entry_list);
76
77         final Collection<WeatherSpecificDataEntry> entries = this.createEmptyEntriesList();
78
79         adapter.addAll(entries);
80         listWeatherView.setAdapter(adapter);
81
82         if (savedInstanceState != null) {
83             // Restore state
84             final WeatherData weatherData = (WeatherData) savedInstanceState
85                     .getSerializable("weatherData");
86             try {
87                 this.storeWeatherDataToFile(weatherData);
88             } catch (final IOException e) {
89                 final DialogFragment newFragment = ErrorDialogFragment
90                         .newInstance(R.string.error_dialog_generic_error);
91                 newFragment.show(this.getFragmentManager(), "errorDialog");
92             }
93         }
94     }
95
96     @Override
97     public void onSaveInstanceState(final Bundle savedInstanceState) {
98
99         // Save state
100         WeatherData weatherData = null;
101         try {
102             weatherData = this.restoreWeatherDataFromFile();
103         } catch (final StreamCorruptedException e) {
104             Log.e(TAG, "onResume exception: ", e);
105         } catch (final FileNotFoundException e) {
106             Log.e(TAG, "onResume exception: ", e);
107         } catch (final IOException e) {
108             Log.e(TAG, "onResume exception: ", e);
109         } catch (final ClassNotFoundException e) {
110             Log.e(TAG, "onResume exception: ", e);
111         }
112
113         if (weatherData != null) {
114             savedInstanceState.putSerializable("weatherData", weatherData);
115         }
116
117         super.onSaveInstanceState(savedInstanceState);
118     }
119
120     @Override
121     public void getWeather() {
122         WeatherData weatherData = null;
123         try {
124             weatherData = this.restoreWeatherDataFromFile();
125         } catch (final StreamCorruptedException e) {
126             Log.e(TAG, "onResume exception: ", e);
127         } catch (final FileNotFoundException e) {
128             Log.e(TAG, "onResume exception: ", e);
129         } catch (final IOException e) {
130             Log.e(TAG, "onResume exception: ", e);
131         } catch (final ClassNotFoundException e) {
132             Log.e(TAG, "onResume exception: ", e);
133         }
134         if (weatherData != null) {
135             this.updateWeatherData(weatherData);
136         }
137     }
138
139     public void updateWeatherData(final WeatherData weatherData) {
140         final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.getDefault());
141         tempFormatter.applyPattern("#####.#####");
142         final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss Z", Locale.getDefault());
143
144         final double tempUnits = this.mIsFahrenheit ? 0 : 273.15;
145
146         final List<WeatherSpecificDataEntry> entries = this.createEmptyEntriesList();
147
148         final ListView listWeatherView = (ListView) this.getActivity().findViewById(
149                 R.id.weather_data_list_view);
150
151         final WeatherSpecificDataAdapter adapter = new WeatherSpecificDataAdapter(this.getActivity(),
152                 R.layout.weather_data_entry_list);
153
154         if (weatherData.getWeather() != null) {
155             entries.set(0, new WeatherSpecificDataEntry(this.getString(R.string.text_field_description), weatherData.getWeather()
156                     .getDescription()));
157             double conversion = weatherData.getMain().getTemp();
158             conversion = conversion - tempUnits;
159             entries.set(1, new WeatherSpecificDataEntry(this.getString(R.string.text_field_tem), tempFormatter.format(conversion)));
160             conversion = weatherData.getMain().getMaxTemp();
161             conversion = conversion - tempUnits;
162             entries.set(2, new WeatherSpecificDataEntry(this.getString(R.string.text_field_tem_max), tempFormatter.format(conversion)));
163             conversion = weatherData.getMain().getMinTemp();
164             conversion = conversion - tempUnits;
165             entries.set(3, new WeatherSpecificDataEntry(this.getString(R.string.text_field_tem_min), tempFormatter.format(conversion)));
166         }
167
168         if (weatherData.getSystem() != null) {
169             long unixTime = weatherData.getSystem().getSunRiseTime();
170             Date unixDate = new Date(unixTime * 1000L);
171             String dateFormatUnix = dateFormat.format(unixDate);
172             entries.set(4, new WeatherSpecificDataEntry(this.getString(R.string.text_field_sun_rise), dateFormatUnix));
173
174             unixTime = weatherData.getSystem().getSunSetTime();
175             unixDate = new Date(unixTime * 1000L);
176             dateFormatUnix = dateFormat.format(unixDate);
177             entries.set(5, new WeatherSpecificDataEntry(this.getString(R.string.text_field_sun_set), dateFormatUnix));
178         }
179
180         if (weatherData.getClouds() != null) {
181             final double cloudiness = weatherData.getClouds().getCloudiness();
182             entries.set(6, new WeatherSpecificDataEntry(this.getString(R.string.text_field_cloudiness), tempFormatter.format(cloudiness)));
183         }
184
185         if (weatherData.getWeather().getIcon() != null) {
186             final Bitmap icon = BitmapFactory.decodeByteArray(
187                     weatherData.getIconData(), 0,
188                     weatherData.getIconData().length);
189             final ImageView imageIcon = (ImageView) this.getActivity()
190                     .findViewById(R.id.weather_picture);
191             imageIcon.setImageBitmap(icon);
192         }
193
194
195
196         listWeatherView.setAdapter(null);
197         adapter.addAll(entries);
198         listWeatherView.setAdapter(adapter);
199     }
200
201     @Override
202     public void onResume() {
203         super.onResume();
204
205         final SharedPreferences sharedPreferences = PreferenceManager
206                 .getDefaultSharedPreferences(this.getActivity());
207
208         // 1. Update units of measurement.
209         String keyPreference = this.getResources().getString(
210                 R.string.weather_preferences_units_key);
211         final String unitsPreferenceValue = sharedPreferences.getString(keyPreference, "");
212         final String celsius = this.getResources().getString(
213                 R.string.weather_preferences_units_celsius);
214         if (unitsPreferenceValue.equals(celsius)) {
215             this.mIsFahrenheit = false;
216         } else {
217             this.mIsFahrenheit = true;
218         }
219
220
221         // 2. Update current data on display.
222         WeatherData weatherData = null;
223         try {
224             weatherData = this.restoreWeatherDataFromFile();
225         } catch (final StreamCorruptedException e) {
226             Log.e(TAG, "onResume exception: ", e);
227         } catch (final FileNotFoundException e) {
228             Log.e(TAG, "onResume exception: ", e);
229         } catch (final IOException e) {
230             Log.e(TAG, "onResume exception: ", e);
231         } catch (final ClassNotFoundException e) {
232             Log.e(TAG, "onResume exception: ", e);
233         }
234         if (weatherData != null) {
235             this.updateWeatherData(weatherData);
236         }
237
238
239         // 3. If language changed, try to retrieve new data for new language
240         // (new strings with the chosen language)
241         keyPreference = this.getResources().getString(
242                 R.string.weather_preferences_language_key);
243         final String languagePreferenceValue = sharedPreferences.getString(
244                 keyPreference, "");
245         if (!languagePreferenceValue.equals(this.mLanguage)) {
246             this.mLanguage = languagePreferenceValue;
247             this.getWeather();
248         }
249     }
250
251     private List<WeatherSpecificDataEntry> createEmptyEntriesList() {
252         final List<WeatherSpecificDataEntry> entries = new ArrayList<WeatherSpecificDataEntry>();
253         entries.add(new WeatherSpecificDataEntry(this.getString(R.string.text_field_description), null));
254         entries.add(new WeatherSpecificDataEntry(this.getString(R.string.text_field_tem), null));
255         entries.add(new WeatherSpecificDataEntry(this.getString(R.string.text_field_tem_max), null));
256         entries.add(new WeatherSpecificDataEntry(this.getString(R.string.text_field_tem_min), null));
257         entries.add(new WeatherSpecificDataEntry(this.getString(R.string.text_field_sun_rise), null));
258         entries.add(new WeatherSpecificDataEntry(this.getString(R.string.text_field_sun_set), null));
259         entries.add(new WeatherSpecificDataEntry(this.getString(R.string.text_field_cloudiness), null));
260         entries.add(new WeatherSpecificDataEntry(this.getString(R.string.text_field_rain_time), null));
261         entries.add(new WeatherSpecificDataEntry(this.getString(R.string.text_field_rain_amount), null));
262         entries.add(new WeatherSpecificDataEntry(this.getString(R.string.text_field_wind_speed), null));
263         entries.add(new WeatherSpecificDataEntry(this.getString(R.string.text_field_humidity), null));
264
265         return entries;
266     }
267
268     private void storeWeatherDataToFile(final WeatherData weatherData)
269             throws FileNotFoundException, IOException {
270         final OutputStream persistenceFile = this.getActivity().openFileOutput(
271                 WEATHER_DATA_FILE, Context.MODE_PRIVATE);
272
273         ObjectOutputStream oos = null;
274         try {
275             oos = new ObjectOutputStream(persistenceFile);
276
277             oos.writeObject(weatherData);
278         } finally {
279             if (oos != null) {
280                 oos.close();
281             }
282         }
283     }
284
285     private WeatherData restoreWeatherDataFromFile() throws StreamCorruptedException,
286     FileNotFoundException, IOException, ClassNotFoundException {
287         final InputStream persistenceFile = this.getActivity().openFileInput(
288                 WEATHER_DATA_FILE);
289
290         ObjectInputStream ois = null;
291         try {
292             ois = new ObjectInputStream(persistenceFile);
293
294             return (WeatherData) ois.readObject();
295         } finally {
296             if (ois != null) {
297                 ois.close();
298             }
299         }
300     }
301 }