/[projects]/android/TrainInfo/src/dk/thoerup/traininfo/StationList.java
ViewVC logotype

Contents of /android/TrainInfo/src/dk/thoerup/traininfo/StationList.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 701 - (show annotations) (download)
Mon May 3 13:41:04 2010 UTC (14 years ago) by torben
File size: 16572 byte(s)
Ugly hack to prevent those auto-reported dialog related exceptions
1 package dk.thoerup.traininfo;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6
7 import android.app.AlertDialog;
8 import android.app.Dialog;
9 import android.app.ListActivity;
10 import android.app.ProgressDialog;
11 import android.content.DialogInterface;
12 import android.content.Intent;
13 import android.content.SharedPreferences;
14 import android.content.SharedPreferences.Editor;
15 import android.location.Location;
16 import android.os.AsyncTask;
17 import android.os.Bundle;
18 import android.os.Handler;
19 import android.os.Message;
20
21 import android.util.Log;
22 import android.view.ContextMenu;
23 import android.view.LayoutInflater;
24 import android.view.Menu;
25 import android.view.MenuItem;
26 import android.view.View;
27 import android.view.ContextMenu.ContextMenuInfo;
28 import android.view.View.OnCreateContextMenuListener;
29 import android.widget.AdapterView;
30 import android.widget.EditText;
31 import android.widget.ListView;
32 import android.widget.Toast;
33 import dk.thoerup.traininfo.provider.ProviderFactory;
34 import dk.thoerup.traininfo.provider.StationProvider;
35 import dk.thoerup.traininfo.stationmap.GeoPair;
36 import dk.thoerup.traininfo.stationmap.StationMapView;
37 import dk.thoerup.traininfo.util.IntSet;
38 import dk.thoerup.traininfo.util.MessageBox;
39
40 import static dk.thoerup.traininfo.R.string.*;
41
42 public class StationList extends ListActivity {
43 public static final int GOTLOCATION = 1001;
44 public static final int GOTSTATIONLIST = 1002;
45 public static final int NOPROVIDER = 1003;
46 public static final int LOCATIONFIXTIMEOUT = 1004;
47
48 public static final int OPTIONS_MAP = 2003;
49 public static final int OPTIONS_GPSINFO = 2004;
50
51
52
53
54 public static final int DLG_PROGRESS = 3001;
55 public static final int DLG_STATIONNAME = 3002;
56
57 static enum LookupMethod {
58 ByLocation,
59 ByName,
60 ByList,
61 MethodNone
62 }
63
64
65 String dialogMessage = "";
66 ProgressDialog dialog;
67 LocationLookup locationLookup = null;
68 FindStationsTask findStationsTask;
69 StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
70
71 GeoPair location = new GeoPair();
72
73 boolean isRunning = false;
74 List<StationBean> stations = new ArrayList<StationBean>();
75
76 StationProvider stationProvider = ProviderFactory.getStationProvider();
77
78 StationListAdapter adapter = null;
79
80 FavoritesMenu contextMenu = new FavoritesMenu();
81 IntSet favorites = new IntSet();
82
83 WelcomeScreen.ListType listType;
84 SharedPreferences prefs;
85
86 ///////////////////////////////////////////////////////////////////////////////////////////
87 //Activity call backs
88
89 @SuppressWarnings("unchecked")
90 @Override
91 public void onCreate(Bundle savedInstanceState) {
92 super.onCreate(savedInstanceState);
93 setContentView(R.layout.stationlist);
94
95
96 adapter = new StationListAdapter(this);
97 setListAdapter(adapter);
98
99 ListView lv = getListView();
100 lv.setOnCreateContextMenuListener(contextMenu);
101
102 locationLookup = new LocationLookup(this, stationsFetched);
103
104
105 prefs = getSharedPreferences("TrainStation", 0);
106 String favoriteString = prefs.getString("favorites", "");
107 if (! favoriteString.equals("") ) {
108 favorites.fromString(favoriteString);
109 }
110
111 listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type");
112 setTitle();
113
114 if (savedInstanceState == null) {
115
116
117 switch (listType) {
118 case ListNearest:
119 startLookup();
120 break;
121 case ListSearch:
122 this.showDialogSafe(DLG_STATIONNAME);
123 break;
124 case ListFavorites:
125 startFavoriteLookup();
126 break;
127 default:
128 // Not possible !?!
129 }
130
131 } else {
132 stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");
133 adapter.setStations(stations);
134 location = (GeoPair) savedInstanceState.getSerializable("location");
135 }
136
137 }
138 protected void setTitle() {
139 String dialogTitle = getResources().getString(app_name);
140 switch (listType) {
141 case ListNearest:
142 dialogTitle += " - " + getString(stationlist_nearbystations);
143 break;
144 case ListSearch:
145 dialogTitle += " - " + getString(stationlist_search);
146 break;
147 case ListFavorites:
148 dialogTitle += " - " + getString(stationlist_favorites);
149 break;
150 default:
151 dialogTitle = "";//not possible
152 }
153
154 setTitle(dialogTitle);
155
156 }
157
158
159 /* these 3 dialogs helper functions are very rude and ugly hack
160 * to remove these auto-reported exceptions
161 * - android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@436aaef8 is not valid; is your activity running?
162 * - java.lang.IllegalArgumentException: View not attached to window manager
163 */
164
165 public void showDialogSafe(int id) {
166 try {
167 showDialog(id);
168 } catch (Exception e) {
169 Log.e("StationList", "showDialog failed", e);
170 }
171 }
172
173 public void dismissDialogSafe(int id) {
174 try {
175 dismissDialog(id);
176 } catch (Exception e) {
177 Log.e("StationList", "dismissDialog failed", e);
178 }
179 }
180
181 public void builderShowSafe(AlertDialog.Builder builder) {
182 try {
183 builder.show();
184 } catch (Exception e) {
185 Log.e("StationList", "builder.show() failed", e);
186 }
187
188 }
189 /* EOF rude and ugly dialog hack */
190
191
192
193 @Override
194 public void onSaveInstanceState(Bundle outState)
195 {
196 if (dialog != null && dialog.isShowing())
197 dialog.dismiss();
198 outState.putSerializable("stations", (ArrayList<StationBean>) stations);
199 outState.putSerializable("location", location);
200
201 }
202
203
204
205 @Override
206 public boolean onCreateOptionsMenu(Menu menu) {
207 MenuItem item;
208
209 item = menu.add(0, OPTIONS_MAP, 0, getString(stationlist_stationmap));
210 item.setIcon(android.R.drawable.ic_menu_mapmode);
211
212 item = menu.add(0, OPTIONS_GPSINFO, 0, getString(stationlist_gpsinfo));
213 item.setIcon(android.R.drawable.ic_menu_mapmode);
214
215 return true;
216 }
217
218 @Override
219 public boolean onOptionsItemSelected(MenuItem item) {
220 boolean retval = true;
221
222 //TODO: Cleanup
223 switch (item.getItemId()) {
224 case OPTIONS_MAP:
225
226 Intent intent = new Intent(this,StationMapView.class);
227
228 ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
229 for (StationBean st : stations ) {
230 stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
231 }
232
233 intent.putExtra("stations", stationPoints);
234
235 startActivity(intent);
236 break;
237 case OPTIONS_GPSINFO:
238 Location loc = locationLookup.getLocation();
239 StringBuffer message = new StringBuffer();
240 message.append( getString(stationlist_locationinfo) ).append(":\n");
241 if (loc != null) {
242 message.append( getString(stationlist_obtainedby) ).append( loc.getProvider() ).append("\n");
243 message.append( getString(stationlist_accuracy) ).append( (int)loc.getAccuracy()).append("m\n");
244 message.append( getString(stationlist_latitude) ).append( (float)loc.getLatitude()).append("\n");
245 message.append( getString(stationlist_longitude) ).append( (float)loc.getLongitude() ).append("\n");
246 } else {
247 message.append( getString(stationlist_nolocation) );
248 }
249
250 MessageBox.showMessage(this, message.toString());
251 break;
252 default:
253 retval = super.onOptionsItemSelected(item);
254 }
255
256 return retval;
257 }
258
259
260
261 @Override
262 public boolean onContextItemSelected(MenuItem item) {
263 contextMenu.onContextItemSelected(item);
264 return true;
265
266
267 }
268
269 public void showMessageAndClose(String message) {
270 AlertDialog.Builder builder = new AlertDialog.Builder(this);
271 builder.setMessage(message)
272 .setCancelable(false)
273 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
274 public void onClick(DialogInterface dialog, int id) {
275 dialog.dismiss();
276 StationList.this.finish();
277 }
278 })
279 .show();
280 }
281
282
283
284
285 @Override
286 protected Dialog onCreateDialog(int id) {
287 switch (id) {
288 case DLG_PROGRESS:
289 ProgressDialog dlg = new ProgressDialog(this);
290 dlg.setMessage( getString(stationlist_waitforlocation) );
291 dlg.setCancelable(false);
292 return dlg;
293 case DLG_STATIONNAME:
294 LayoutInflater factory = LayoutInflater.from(this);
295 final View rootView = factory.inflate(R.layout.textinput, null);
296
297
298 AlertDialog.Builder builder = new AlertDialog.Builder(this);
299
300 builder.setTitle( getString(stationlist_stationsearch) );
301 builder.setView(rootView);
302 builder.setCancelable(true);
303 builder.setPositiveButton( getString(generic_search), new DialogInterface.OnClickListener() {
304 public void onClick(DialogInterface dialog, int which) {
305 EditText et = (EditText) rootView.findViewById(R.id.EditText);
306 dialog.dismiss();
307 if (et.getText().toString().length() >= 2) {
308 startNameSearch(et.getText().toString());
309 } else {
310 showMessageAndClose( getString(stationlist_twocharmin) );
311 }
312 }
313 });
314 builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
315 public void onClick(DialogInterface dialog, int which) {
316 dialog.dismiss();
317 StationList.this.finish(); // Close this Activity
318 }
319 });
320 return builder.create();
321
322 default:
323 return super.onCreateDialog(id);
324 }
325
326 }
327
328
329 @Override
330 protected void onPrepareDialog(int id, Dialog dialog) {
331 super.onPrepareDialog(id, dialog);
332 switch (id) {
333 case DLG_PROGRESS:
334 this.dialog = (ProgressDialog) dialog;
335 if (!dialogMessage.equals("")) {
336 this.dialog.setMessage(dialogMessage);
337 dialogMessage = "";
338 }
339 break;
340 }
341 }
342
343 @Override
344 protected void onListItemClick(ListView l, View v, int position, long id) {
345 super.onListItemClick(l, v, position, id);
346
347 StationBean station = stations.get(position);
348
349 Intent intent = new Intent(this, DepartureList.class);
350 intent.putExtra("stationbean", station);
351 startActivity(intent);
352 }
353
354 /////////////////////////////////////////////////////////////
355 //
356
357 public void startLookup() {
358 isRunning = true;
359 dialogMessage = getString( stationlist_waitforlocation );
360 showDialogSafe(DLG_PROGRESS);
361
362 locationLookup.locateStations();
363 stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000);
364 }
365
366 void startNameSearch(String name) {
367 dialogMessage = getString( stationlist_findbyname );
368 showDialogSafe(DLG_PROGRESS);
369
370 findStationsTask = new FindStationsTask();
371 findStationsTask.searchByName(name);
372 findStationsTask.execute();
373
374 }
375
376 public void startFavoriteLookup() {
377
378 if (favorites.size() > 0) {
379 dialogMessage = getString( stationlist_loadfavorites );
380 showDialogSafe(DLG_PROGRESS);
381
382 findStationsTask = new FindStationsTask();
383 findStationsTask.searchByIds( favorites.toString() );
384 findStationsTask.execute();
385 } else {
386 showMessageAndClose( getString( stationlist_nofavorites ) );
387 }
388 }
389
390
391
392 void startLocatorTask()
393 {
394 dialogMessage = getString( stationlist_findingnearby );
395 showDialogSafe(DLG_PROGRESS);
396
397 findStationsTask = new FindStationsTask();
398 findStationsTask.searchByLocation( locationLookup.getLocation() );
399 findStationsTask.execute();
400 }
401
402
403 ////////////////////////////////////////////////////////////////////////////
404 // Inner classes
405
406 class StationsFetchedHandler extends Handler {
407 @Override
408 public void handleMessage(Message msg) {
409
410 switch (msg.what) {
411 case GOTLOCATION:
412 dismissDialogSafe(DLG_PROGRESS);
413
414 startLocatorTask();
415 location = GeoPair.fromLocation( locationLookup.getLocation() );
416
417 break;
418
419 case NOPROVIDER:
420 dismissDialogSafe(DLG_PROGRESS);
421 MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider) );
422 break;
423 case LOCATIONFIXTIMEOUT:
424 if (isRunning) {
425 locationLookup.stopSearch();
426 if (locationLookup.hasLocation()) {
427 stationsFetched.sendEmptyMessage( GOTLOCATION );
428 } else {
429 dismissDialogSafe(DLG_PROGRESS);
430
431 AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);
432 builder.setMessage( getString( stationlist_gpstimeout) );
433 builder.setCancelable(true);
434 builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
435 public void onClick(DialogInterface dialog, int id) {
436 dialog.dismiss();
437 startLookup();
438
439 }
440 });
441 builder.setNegativeButton( getString(generic_cancel), new DialogInterface.OnClickListener() {
442 public void onClick(DialogInterface dialog, int id) {
443 dialog.dismiss();
444 }
445 });
446 builderShowSafe(builder); // builder.show()
447
448 }
449 }
450 break;
451 }
452 isRunning = false;
453 }
454 };
455
456
457 class FindStationsTask extends AsyncTask<Void,Void,Void> {
458
459 LookupMethod method = LookupMethod.MethodNone;
460 boolean success;
461 String name;
462 Location loc;
463 String ids;
464
465 public void searchByName(String n) {
466
467 method = LookupMethod.ByName;
468 name = n;
469 }
470
471 public void searchByLocation(Location l) {
472 method = LookupMethod.ByLocation;
473 loc = l;
474 }
475
476 public void searchByIds(String id) {
477
478 method = LookupMethod.ByList;
479 ids = id;
480 }
481
482 @Override
483 protected void onPreExecute() {
484
485 if (method.equals(LookupMethod.MethodNone))
486 throw new RuntimeException("Method not set");
487 super.onPreExecute();
488 }
489
490 @Override
491 protected Void doInBackground(Void... params) {
492
493 switch (method) {
494 case ByLocation:
495 success = stationProvider.lookupStations(loc);
496 break;
497 case ByName:
498 success = stationProvider.lookupStationsByName(name);
499 break;
500 case ByList:
501 success = stationProvider.lookupStationsByIds(ids);
502 break;
503 default:
504 success = false; // not possible
505 }
506
507
508 return null;
509 }
510
511 @Override
512 protected void onPostExecute(Void result) {
513 super.onPostExecute(result);
514 dialog.dismiss();
515
516
517 if (success) {
518 if (stationProvider.getStations().size() == 0) {
519 showMessageAndClose(getString(stationlist_nostations));
520 }
521 stations = stationProvider.getStations();
522 adapter.setStations( stations );
523
524 } else { //communication or parse errors
525 AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);
526 builder.setMessage(getString(stationlist_nearbyerror));
527 builder.setCancelable(true);
528 builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
529 public void onClick(DialogInterface dialog, int id) {
530 dialog.dismiss();
531
532 Runnable runner = null;
533 switch (method) {
534 case ByLocation:
535 runner = new Runnable() {
536 @Override
537 public void run() {
538 startLocatorTask();
539 }
540 };
541 break;
542 case ByName:
543 runner = new Runnable() {
544 @Override
545 public void run() {
546 startNameSearch( FindStationsTask.this.name );
547 }
548 };
549 break;
550 case ByList:
551 runner = new Runnable() {
552 @Override
553 public void run() {
554 startFavoriteLookup();
555 }
556 };
557 break;
558 }
559
560 stationsFetched.post( runner );
561 }
562 });
563 builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
564 public void onClick(DialogInterface dialog, int id) {
565 dialog.dismiss();
566 }
567 });
568
569 builderShowSafe(builder); // builder.show()
570 }
571 }
572 }
573
574
575 class FavoritesMenu implements OnCreateContextMenuListener {
576 private final static int FAVORITES_ADD = 9001;
577 private final static int FAVORITES_REMOVE = 9002;
578
579 private int selectedPosition;
580
581
582 @Override
583 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
584
585 AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
586 selectedPosition = info.position;
587 int stationID = stations.get(selectedPosition).getId();
588
589 if (!favorites.contains(stationID)) {
590 menu.add(0, FAVORITES_ADD, 0, getString(stationlist_addfavorite) );
591 } else {
592 menu.add(0, FAVORITES_REMOVE, 0, getString(stationlist_removefavorite) );
593 }
594
595 }
596
597 public void onContextItemSelected(MenuItem item) {
598 StationBean sb = stations.get(selectedPosition);
599
600 int stationID = sb.getId();
601 if (item.getItemId() == FAVORITES_ADD) {
602 favorites.add(stationID);
603 Toast.makeText(StationList.this, getString(stationlist_stationadded), Toast.LENGTH_SHORT).show();
604 } else {
605
606 favorites.remove(stationID);
607 Toast.makeText(StationList.this, getString(stationlist_stationremoved), Toast.LENGTH_SHORT).show();
608
609
610 if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) {
611 stations.remove(selectedPosition);
612 adapter.notifyDataSetChanged();
613 }
614 }
615 Editor ed = prefs.edit();
616 ed.putString("favorites", favorites.toString());
617 ed.commit();
618 }
619 }
620 }

  ViewVC Help
Powered by ViewVC 1.1.20