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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.20