Bonjour. Dans le cadre de mon éjour Erasmus au Danemark, je dois réaliser une application qui accède aux données météo de la ville d'Aarhus et les affiche dans une activity. L'appli doit également se connecter à intervalles de temps réguliers (30 minutes) à l'API Open Weather Map, récupérer les donénes et les stocker dans une base SQLite pour pouvoir afficher l'historique des conditions météo grâce à une listView (étant donné que l'API permet seulement d'avoir accès aux conditions actuelles via la version gratuite).
Je dispose de six classes en tout :
- WeatherActivity
- WeatherDatabaseHelper
- WeatherInfo(permet de récupérer les données chargées par le service)
- WeatherPastObj(création d'une objet indiquant les conditions météo à un moment donné)
- WeatherPastObjAdapter (pour récupérer l'historique dans une listView)
- WeatherService (connection à l'API et récupération des données via une asyncTask et une requête http)
Voici mon code :
--------------------------------------------------------------------------------------WeatherActivity------------------------------------------------------------------
Code Java : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112 import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; public class WeatherActivity extends AppCompatActivity { WeatherService weatherService; ListView weatherHistoric; protected WeatherPastObjAdapter weatherAdapter; protected ArrayList<WeatherInfo> weatherHistory; protected WeatherInfo weatherCurrent; protected PendingIntent alarmIntent; boolean bound = false; ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { WeatherService.LocalWeatherBinder weatherBinder = (WeatherService.LocalWeatherBinder)service; weatherService = weatherBinder.getBinder(); bound = true; } @Override public void onServiceDisconnected(ComponentName name) { bound = false; } }; protected void onStart() { super.onStart(); Intent intent = new Intent(WeatherActivity.this, WeatherService.class); bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE); } protected void onStop() { super.onStop(); if(bound) { unbindService(mServiceConnection); bound = false; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(WeatherActivity.this, WeatherService.class); startService(intent); alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); displayCurrentWeather(); displayHistoricWeather(); } private void displayCurrentWeather() { weatherCurrent = new WeatherInfo(); weatherCurrent = weatherService.getCurrentWeather(); } private void displayHistoricWeather() { try { weatherHistory = new ArrayList<>(); weatherHistory = weatherService.getWeatherHistory(); } catch(Exception e) { Log.d("Error","getWeatherHistory : displayHistoricWeather",e); } int entries = weatherHistory.size(); WeatherPastObj[] weatherObjs = new WeatherPastObj[entries]; for(int i = 0; i<entries; i++) { weatherAdapter.clear(); String city = weatherHistory.get(i).getCity().toString(); String temperature = weatherHistory.get(i).getNameDescription(); String name_description = weatherHistory.get(i).getTimestamp().toString(); String description = weatherHistory.get(i).getNameDescription(); String humidity = weatherHistory.get(i).getTimestamp().toString(); String pressure = weatherHistory.get(i).getNameDescription(); String weatherIcon = weatherHistory.get(i).getTimestamp().toString(); String timestamp = weatherHistory.get(i).getNameDescription(); weatherObjs[i] = new WeatherPastObj(city, temperature, name_description, description, humidity, pressure, weatherIcon, timestamp); weatherAdapter.add(weatherObjs[i]); } weatherHistoric = (ListView)findViewById(R.id.WeatherHistoric); weatherHistoric.setAdapter(weatherAdapter); } }
-----------------------------------------------------------------------------------WeatherService---------------------------------------------------------------------
Code Java : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414 import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import android.app.Service; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; public class WeatherService extends Service { public final IBinder WeatherServiceBinder = new LocalWeatherBinder(); public WeatherHttpRequest ArhusRequest; public WeatherDatabaseHelper WeatherDatabase; public WeatherBDD WeatherBdd; public WeatherInfo currentWeather; public class LocalWeatherBinder extends Binder { WeatherService getBinder() { // Return this instance of LocalService so clients can call public methods return WeatherService.this; } } public WeatherService() { } @Override public void onCreate() { super.onCreate(); } public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { long delay = 0; long period = 1800000; ArhusRequest = new WeatherHttpRequest(); ArhusRequest.getWeatherData("Arhus"); WeatherBdd = new WeatherBDD(getApplicationContext()); MyCityTimerTask myTimerTask = new MyCityTimerTask(); Timer myTimer = new Timer(); myTimer.schedule(myTimerTask, delay, period); } return START_STICKY; } @Override public IBinder onBind(Intent intent) { return WeatherServiceBinder; } @Override public boolean onUnbind(Intent intent) { return super.onUnbind(intent); } @Override public void onDestroy() { super.onDestroy(); } public WeatherInfo getCurrentWeather() { WeatherInfo currentWeather = new WeatherInfo(); SQLiteDatabase db = WeatherBdd.openReadable(); String query = "SELECT * FROM " + WeatherBdd.TABLE_NAME + " WHERE " + WeatherBdd.COL_HISTORIC_ID + " = MAX(" + WeatherBdd.COL_HISTORIC_ID + ")"; Cursor cursor = db.rawQuery(query, null); try { if (cursor.moveToFirst()) { currentWeather.setTemperature(cursor.getString(0)); currentWeather.setNameDescription(cursor.getString(1)); currentWeather.setDescription(cursor.getString(2)); currentWeather.setTimestamp(cursor.getLong(3)); } } catch (Exception e) { Log.d("Error", "getCurrentWeather", e); } finally { cursor.close(); } return currentWeather; } //Returns the current weather history of the last 24 hours public ArrayList<WeatherInfo> getWeatherHistory() { ArrayList<WeatherInfo> weatherHistory = new ArrayList<>(); SQLiteDatabase db = WeatherBdd.openReadable(); String query = "SELECT * FROM " + WeatherBdd.TABLE_NAME + " ORDER BY " + WeatherBdd.COL_HISTORIC_ID + " DESC LIMIT 48"; Cursor cursor = db.rawQuery(query, null); try { if (cursor.moveToFirst()) { while (cursor.moveToNext() && !cursor.isLast()) { WeatherInfo infos = new WeatherInfo(); infos.setTemperature(cursor.getString(0)); infos.setNameDescription(cursor.getString(1)); infos.setDescription(cursor.getString(2)); infos.setTimestamp(cursor.getLong(3)); weatherHistory.add(infos); } } } catch (Exception e) { Log.d("Error", "getWeatherHistory", e); } finally { cursor.close(); } return weatherHistory; } public String setWeatherIcon(int actualId, long sunrise, long sunset) { int id = actualId / 100; String icon = ""; if (actualId == 800) { long currentTime = new Date().getTime(); if (currentTime >= sunrise && currentTime < sunset) { icon = getApplicationContext().getString(R.string.weather_sunny); } else { icon = getApplicationContext().getString(R.string.weather_clear_night); } } else { switch (id) { case 2: icon = getApplicationContext().getString(R.string.weather_foggy); break; case 3: icon = getApplicationContext().getString(R.string.weather_cloudy); break; case 7: icon = getApplicationContext().getString(R.string.weather_rainy); break; case 8: icon = getApplicationContext().getString(R.string.weather_snowy); break; case 6: icon = getApplicationContext().getString(R.string.weather_thunder); break; case 5: icon = getApplicationContext().getString(R.string.weather_drizzle); break; } } return icon; } public interface AsyncResponse { void processFinish(String output1, String output2, String output3, String output4, String output5, String output6, String output7, String output8); } public class MyCityTask extends AsyncTask<String, Void, JSONObject> { public AsyncResponse delegate = null;//Call back interface public MyCityTask(AsyncResponse delegate) { this.delegate = delegate;//Assigning call back interfacethrough constructor } @Override protected JSONObject doInBackground(String... params) { Looper looper = Looper.getMainLooper(); looper.prepare(); looper.loop(); JSONObject jsonWeather = null; try { jsonWeather = ArhusRequest.getWeatherData(params[0]); } catch (Exception e) { Log.d("Error", "Cannot process JSON results", e); } return jsonWeather; } @Override protected void onPostExecute(JSONObject json) { try { if (json != null) { JSONObject details = json.getJSONArray("weather").getJSONObject(0); JSONObject main = json.getJSONObject("main"); DateFormat df = DateFormat.getDateTimeInstance(); String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country"); String temperature = String.format("%.2f", main.getDouble("temp")) + "°"; String name_description = details.getString("main").toUpperCase(Locale.US); String description = details.getString("description").toUpperCase(Locale.US); String humidity = main.getString("humidity") + "%"; String pressure = main.getString("pressure") + " hPa"; String timestamp = df.format(new Date(json.getLong("dt") * 1000)); String iconText = setWeatherIcon(details.getInt("id"), json.getJSONObject("sys").getLong("sunrise") * 1000, json.getJSONObject("sys").getLong("sunset") * 1000); delegate.processFinish(city, temperature, name_description, description, humidity, pressure, iconText, timestamp); } } catch (JSONException e) { //Log.e(LOG_TAG, "Cannot process JSON results", e); } } } public class MyCityTimerTask extends TimerTask { public void run() { MyCityTask asyncTask = new MyCityTask(new AsyncResponse() { public void processFinish(String weather_city, String weather_temperature, String weather_name, String weather_description, String weather_humidity, String weather_pressure, String weather_iconText, String time_stamp) { Long timeStamp = Long.parseLong(time_stamp); currentWeather = new WeatherInfo(); currentWeather.setCity(weather_city); currentWeather.setTemperature(weather_temperature); currentWeather.setNameDescription(weather_name); currentWeather.setDescription(weather_description); currentWeather.setHumidity(weather_humidity); currentWeather.setPressure(weather_pressure); currentWeather.setIcon(weather_iconText); currentWeather.setTimestamp(timeStamp); try { WeatherBdd.insertCurrentWeatherDatas(weather_temperature, weather_name, weather_description, weather_humidity, weather_pressure, weather_iconText, time_stamp); } catch (Exception e) { Log.d("Error", "MyCityTask or MyCityTimerTask", e); } finally { WeatherBdd.removeOldWeatherDatas(); } } }); asyncTask.execute(); } } public class WeatherHttpRequest { private String OPEN_WEATHER_MAP_API = "http://api.openweathermap.org/data/2.5/weather?q=%s&units=metric"; public JSONObject getWeatherData(String city) { HttpURLConnection connection = null; BufferedReader reader = null; StringBuffer json = null; try { URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city)); connection = (HttpURLConnection) url.openConnection(); connection.addRequestProperty("x-api-key", getApplicationContext().getString(R.string.open_weather_map_api_key)); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); json = new StringBuffer(); String tmp; while ((tmp = reader.readLine()) != null) { json.append(tmp).append("\n"); reader.close(); } JSONObject data = new JSONObject(json.toString()); // This value will be 404 if the request was not // successful if (data.getInt("cod") != 200) { return null; } else { return data; } } catch (Exception e) { Log.d("Error", "WeatherHttpRequest getWeatherData", e); return null; } } } public class WeatherBDD { public final String TABLE_NAME = "historic_weather"; public final String COL_HISTORIC_ID = null; public final String COL_WEATHER_TEMPERATURE = null; public final String COL_WEATHER_NAME = null; public final String COL_WEATHER_DESCRIPTION = null; public final String COL_LEVEL_HUMIDITY = null; public final String COL_LEVEL_PRESSURE = null; public final String COL_WEATHER_ICON = null; public final String COL_TIMESTAMP = null; private SQLiteDatabase bdd; private WeatherDatabaseHelper myBaseSQLite; public WeatherBDD(Context context){ myBaseSQLite = new WeatherDatabaseHelper(context); } public SQLiteDatabase openWritable(){ bdd = myBaseSQLite.getWritableDatabase(); return bdd; } public SQLiteDatabase openReadable() { bdd = myBaseSQLite.getReadableDatabase(); return bdd; } public void close(){ bdd.close(); } public SQLiteDatabase getBDD(){ return bdd; } public long insertCurrentWeatherDatas(String weather_temperature, String weather_name, String weather_desc, String weather_humidity, String weather_pressure, String weather_icon, String weather_time){ ContentValues values = new ContentValues(); values.put(COL_WEATHER_TEMPERATURE, weather_temperature); values.put(COL_WEATHER_NAME, weather_name); values.put(COL_WEATHER_DESCRIPTION, weather_desc); values.put(COL_LEVEL_HUMIDITY, weather_humidity); values.put(COL_LEVEL_PRESSURE, weather_pressure); values.put(COL_WEATHER_ICON, weather_icon); values.put(COL_TIMESTAMP, weather_time); return bdd.insert(TABLE_NAME, null, values); } private void removeOldWeatherDatas() { try { bdd = openWritable(); } catch(Exception e) { Log.d("Error", "removeOldWeatherDatas", e); } long now = System.currentTimeMillis() / 1000L; long old = now - 24*60*60; //24 hours String query = "DELETE FROM " + myBaseSQLite.TABLE_NAME + " WHERE " + myBaseSQLite.COL_TIMESTAMP + " < " + Long.toString(old); bdd.execSQL(query); } } }
------------------------------------------------------------------------------WeatherInfo------------------------------------------------------------------------------
Code Java : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125 public class WeatherInfo { protected String city; protected String temperature; protected String name_description; protected String description; protected String humidity; protected String pressure; protected String weatherIcon; protected Long timeStamp; public WeatherInfo(String city, String temperature, String name_description, String description, String humidity, String pressure, String weatherIcon, Long timeStamp) { setCity(city); setTemperature(temperature); setNameDescription(name_description); setDescription(description); setHumidity(humidity); setPressure(pressure); setIcon(weatherIcon); setTimestamp(timeStamp); } public WeatherInfo() { } public void setCity(String city) { this.city = city; } public void setNameDescription(String nameDesc) { this.name_description = nameDesc; } public void setDescription(String Desc) { this.description = Desc; } public void setTemperature(String temp) { this.temperature = temp; } public void setHumidity(String humidity) { this.humidity = humidity; } public void setIcon(String weatherIcon) { this.weatherIcon = weatherIcon; } public void setPressure(String pressure) { this.pressure = pressure; } public void setTimestamp(Long timestamp) { this.timeStamp = timestamp; } public String getCity() { return city; } public String getNameDescription() { return name_description; } public String getDescription() { return description; } public String getTemperature() { return temperature; } public String getHumidity() { return humidity; } public String getPressure() { return pressure; } public String getWeatherIcon() { return weatherIcon; } public Long getTimestamp() { return timeStamp; } }
---------------------------------------------------------------------------------------WeatherPastObj-----------------------------------------------------------------
Code Java : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120 public class WeatherPastObj{ protected String city; protected String temperature; protected String name_description; protected String description; protected String humidity; protected String pressure; protected String weather_icon; protected String timestamp; public WeatherPastObj(String city, String temperature, String name_description, String description, String humidity, String pressure, String weather_icon, String timestamp){ this.city = city; this.temperature = temperature; this.name_description = name_description; this.description = description; this.humidity = humidity; this.pressure = pressure; this.weather_icon = weather_icon; this.timestamp = timestamp; } public WeatherPastObj() { } public String getCity() { return city; } public String getTemperature() { return temperature; } public String getNameDecription() { return name_description; } public String getDescription() { return description; } public String getHumidity() { return humidity; } public String getPressure() { return pressure; } public String getWeatherIcon() { return weather_icon; } public String getTimeStamp() { return timestamp; } public void setCity(String city) { this.city = city; } public void setTemperature(String temperature) { this.temperature = temperature; } public void setNameDecription(String name_description) { this.name_description = name_description; } public void setDescription(String description) { this.description = description; } public void setHumidity(String humidity) { this.humidity = humidity; } public void setPressure(String pressure) { this.pressure = pressure; } public void setWeatherIcon(String weather_icon) { this.weather_icon = weather_icon; } public void setTimeStamp(String timestamp) { this.timestamp = timestamp; } }
---------------------------------------------------------------------------------WeatherPastObjAdapter--------------------------------------------------------------
Code Java : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62 import android.content.Context; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; /** * Created by ASUS on 05/10/2016. */ public class WeatherPastObjAdapter extends ArrayAdapter<WeatherPastObj> { private Context context; private ArrayList<WeatherPastObj> weatherPastConditions; public WeatherPastObjAdapter(Context context, ArrayList<WeatherPastObj> weatherPastConditions) { super(context, R.layout.item_historic_weather, weatherPastConditions); this.context = context; this.weatherPastConditions = weatherPastConditions; } @Override public View getView(int position, View convertView, ViewGroup parent) { View itemView = convertView; if (itemView == null) { LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); itemView = vi.inflate(R.layout.item_historic_weather, null); } WeatherPastObj obj = weatherPastConditions.get(position); if (obj!= null) { TextView item_city_field = (TextView)itemView.findViewById(R.id.item_city_field); TextView item_current_temperature_field = (TextView)itemView.findViewById(R.id.item_current_temperature_field); TextView item_humidity_field = (TextView) itemView.findViewById(R.id.item_humidity_field); TextView item_pressure_field = (TextView) itemView.findViewById(R.id.item_pressure_field); TextView item_weather_icon = (TextView) itemView.findViewById(R.id.item_weather_icon); TextView item_timestamp = (TextView)itemView.findViewById(R.id.item_timestamp); item_city_field.setText(obj.getCity()); item_current_temperature_field.setText(obj.getTemperature()); item_humidity_field.setText(obj.getHumidity()); item_pressure_field.setText(obj.getPressure()); item_weather_icon.setText(Html.fromHtml(obj.getWeatherIcon())); item_timestamp.setText(obj.getTimeStamp()); } return itemView; } }
-----------------------------------------------------------------------------WeatherDatabaseHelper------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Code Java : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.Calendar; public class WeatherDatabaseHelper extends SQLiteOpenHelper { public static final String TABLE_NAME = "historic_weather"; public static final String COL_HISTORIC_ID = "id"; public static final String COL_WEATHER_TEMPERATURE = "temperature"; public static final String COL_WEATHER_HUMIDITY = "weather"; public static final String COL_WEATHER_PRESSURE = "weather_description"; public static final int COL_TIMESTAMP = Calendar.getInstance().get(Calendar.DATE); private static final String CREATE_BDD = "CREATE TABLE " + TABLE_NAME + " (" + COL_HISTORIC_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_WEATHER_TEMPERATURE + " TEXT NOT NULL" + COL_WEATHER_HUMIDITY + " TEXT NOT NULL, " + COL_WEATHER_PRESSURE + " TEXT NOT NULL, " + COL_TIMESTAMP + " TEXT NOT NULL " + " )"; private static final String DATABASE_NAME = "aarhus_weather.db"; private static final int DATABASE_VERSION = 1; public WeatherDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_BDD); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE " + TABLE_NAME + ";"); onCreate(db); } }
J'ai beau faire, mon appli crashe toujours à la fin
J'obtiens le message d'erreur suivant :
Your solution must have three main components and talk to an external web server:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 10-07 15:43:28.646 2676-2676/com.example.asus.weather_aarhus_groupe_tc I/art: Not late-enabling -Xcheck:jni (already on) 10-07 15:43:28.840 2676-2682/com.example.asus.weather_aarhus_groupe_tc I/art: Debugger is no longer active 10-07 15:43:29.016 2676-2676/com.example.asus.weather_aarhus_groupe_tc W/System: ClassLoader referenced unknown path: /data/app/com.example.asus.weather_aarhus_groupe_tc-1/lib/x86 10-07 15:43:30.229 2676-2676/com.example.asus.weather_aarhus_groupe_tc D/AndroidRuntime: Shutting down VM 10-07 15:43:30.230 2676-2676/com.example.asus.weather_aarhus_groupe_tc E/AndroidRuntime: FATAL EXCEPTION: main 10-07 15:44:43.929 2676-2682/com.example.asus.weather_aarhus_groupe_tc W/art: Suspending all threads took: 5.098ms 10-07 15:47:31.357 2676-2682/com.example.asus.weather_aarhus_groupe_tc W/art: Suspending all threads took: 10.646ms 10-07 15:48:27.656 2676-2682/com.example.asus.weather_aarhus_groupe_tc W/art: Suspending all threads took: 5.012ms 10-07 15:48:30.784 2676-2676/com.example.asus.weather_aarhus_groupe_tc I/Process: Sending signal. PID: 2676 SIG: 9 10-07 16:21:00.667 2990-2990/com.example.asus.weather_aarhus_groupe_tc I/art: Not late-enabling -Xcheck:jni (already on) 10-07 16:21:01.214 2990-2990/com.example.asus.weather_aarhus_groupe_tc W/System: ClassLoader referenced unknown path: /data/app/com.example.asus.weather_aarhus_groupe_thomas_charles-1/lib/x86 10-07 16:21:01.556 2990-2990/com.example.asus.weather_aarhus_groupe_tc D/AndroidRuntime: Shutting down VM --------- beginning of crash 10-07 16:21:01.557 2990-2990/com.example.asus.weather_aarhus_groupe_tc E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.asus.weather_aarhus_groupe_tc, PID: 2990 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.asus.weather_aarhus_groupe_tc/com.example.asus.weather_aarhus_groupe_tc.WeatherActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.asus.weather_aarhus_groupe_tc.WeatherInfo com.example.asus.weather_aarhus_groupe_tc.WeatherService.getCurrentWeather()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.asus.weather_aarhus_groupe_thomas_charles.WeatherInfo com.example.asus.weather_aarhus_groupe_thomas_charles.WeatherService.getCurrentWeather()' on a null object reference at com.example.asus.weather_aarhus_groupe_thomas_charles.WeatherActivity.displayCurrentWeather(WeatherActivity.java:77) at com.example.asus.weather_aarhus_groupe_thomas_charles.WeatherActivity.onCreate(WeatherActivity.java:69) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)* at android.app.ActivityThread.-wrap11(ActivityThread.java)* at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)* at android.os.Handler.dispatchMessage(Handler.java:102)* at android.os.Looper.loop(Looper.java:148)* at android.app.ActivityThread.main(ActivityThread.java:5417)* at java.lang.reflect.Method.invoke(Native Method)* at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)* at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)* 10-07 16:21:32.727 2990-2996/com.example.asus.weather_aarhus_groupe_tc W/art: Suspending all threads took: 13.151ms
An Activity: the Activity will use the Service to get up-to-date data and show it to the user. It should also allow the user to refresh and check for new data manually.
A database: a small database and functionality to store weather information entries (hint: create a DatabaseHelper class). The database will be used by the Service.
A Service: this should be a Background service that manages the database AND periodically retrieves new weather information from the web service. As such the Service should always have the newest data and the Activity can get it when needed.
Further details on requirements for assignment:
To communicate between the service/activity and service/database you must use a WeatherInfo “model” class that holds AT LEAST the following information:
ID (corresponding to database entry)
Weather description (text)
Temperature (in celcius)
Timestamp (when the data is from)
The activity should show the current weather in whatever way you want to present it (above diagram could be a starting point), but it should visualize all the information from the WeatherInfo class.
The activity should show the weather data for every 30 minutes from up to 24 hours in the past. You should use a ListView with an Adaptor for this. You can use an existing adaptor or create a custom adaptor that takes a list of WeatherObjects with custom XML layout.
The background service should run all the time (from the first time the app is started)
The Activity bind to the service when active and retrieve the most up-to-date weather data through two methods, like these:
WeatherInfo getCurrentWeather()
List<WeatherInfo> getPastWeather()
The Service should send out a local broadcast when there is new weather data available. The Activity should register for this, and update the UI if needed.
The background service must call the OpenWeatherMap server every 30 minutes and save the results in the database.
You must have a custom icon for your app
You app name should be “Weather Aarhus group XX” where XX is your group number.
You should include LogCat outputs / logging to validate that the service is running
All resources used should be externalized
Style the app with your own colors
Partager