/[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 984 - (hide annotations) (download)
Sun Jul 11 15:29:13 2010 UTC (13 years, 10 months ago) by torben
File size: 17851 byte(s)
clean imports
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 433 import android.view.ContextMenu;
23 torben 381 import android.view.LayoutInflater;
24 torben 368 import android.view.Menu;
25     import android.view.MenuItem;
26 torben 237 import android.view.View;
27 torben 433 import android.view.ContextMenu.ContextMenuInfo;
28     import android.view.View.OnCreateContextMenuListener;
29     import android.widget.AdapterView;
30 torben 381 import android.widget.EditText;
31 torben 237 import android.widget.ListView;
32 torben 433 import android.widget.Toast;
33 torben 319 import dk.thoerup.traininfo.provider.ProviderFactory;
34     import dk.thoerup.traininfo.provider.StationProvider;
35 torben 368 import dk.thoerup.traininfo.stationmap.GeoPair;
36     import dk.thoerup.traininfo.stationmap.StationMapView;
37 torben 433 import dk.thoerup.traininfo.util.IntSet;
38 torben 245 import dk.thoerup.traininfo.util.MessageBox;
39 torben 237
40 torben 561 import static dk.thoerup.traininfo.R.string.*;
41    
42 torben 336 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 torben 368
48 torben 381 public static final int OPTIONS_MAP = 2003;
49 torben 481 public static final int OPTIONS_GPSINFO = 2004;
50 torben 433
51 torben 381 public static final int DLG_PROGRESS = 3001;
52     public static final int DLG_STATIONNAME = 3002;
53 torben 237
54 torben 948
55     public static final int GPS_TIMEOUT_MS = 17500; //how long are we willing to wait for gps fix -in milliseconds
56    
57    
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 torben 983 case ListSearch:
126     showDialog(DLG_STATIONNAME); //TODO: 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 torben 983
185     /*
186 torben 701 public void showDialogSafe(int id) {
187     try {
188     showDialog(id);
189     } catch (Exception e) {
190     Log.e("StationList", "showDialog failed", e);
191     }
192     }
193    
194     public void dismissDialogSafe(int id) {
195     try {
196     dismissDialog(id);
197     } catch (Exception e) {
198     Log.e("StationList", "dismissDialog failed", e);
199     }
200     }
201 torben 725 public void dismissDialogSafe(Dialog dlg) {
202     try {
203     dlg.dismiss();
204     } catch (Exception e) {
205     Log.e("StationList", "dismissDialog failed", e);
206     }
207     }
208 torben 701
209     public void builderShowSafe(AlertDialog.Builder builder) {
210     try {
211     builder.show();
212     } catch (Exception e) {
213     Log.e("StationList", "builder.show() failed", e);
214     }
215    
216 torben 983 }*/
217    
218 torben 701 /* EOF rude and ugly dialog hack */
219    
220 torben 371
221    
222 torben 243 @Override
223     public void onSaveInstanceState(Bundle outState)
224     {
225 torben 258 if (dialog != null && dialog.isShowing())
226 torben 243 dialog.dismiss();
227 torben 258 outState.putSerializable("stations", (ArrayList<StationBean>) stations);
228 torben 374 outState.putSerializable("location", location);
229 torben 482
230 torben 243 }
231 torben 237
232 torben 243
233 torben 237
234     @Override
235 torben 368 public boolean onCreateOptionsMenu(Menu menu) {
236 torben 419 MenuItem item;
237 torben 561
238     item = menu.add(0, OPTIONS_MAP, 0, getString(stationlist_stationmap));
239 torben 419 item.setIcon(android.R.drawable.ic_menu_mapmode);
240    
241 torben 561 item = menu.add(0, OPTIONS_GPSINFO, 0, getString(stationlist_gpsinfo));
242 torben 481 item.setIcon(android.R.drawable.ic_menu_mapmode);
243    
244 torben 368 return true;
245     }
246    
247     @Override
248     public boolean onOptionsItemSelected(MenuItem item) {
249 torben 381 boolean retval = true;
250    
251 torben 481 //TODO: Cleanup
252 torben 368 switch (item.getItemId()) {
253     case OPTIONS_MAP:
254    
255     Intent intent = new Intent(this,StationMapView.class);
256    
257     ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
258     for (StationBean st : stations ) {
259 torben 369 stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
260 torben 368 }
261    
262     intent.putExtra("stations", stationPoints);
263    
264     startActivity(intent);
265     break;
266 torben 481 case OPTIONS_GPSINFO:
267 torben 482 Location loc = locationLookup.getLocation();
268 torben 371 StringBuffer message = new StringBuffer();
269 torben 561 message.append( getString(stationlist_locationinfo) ).append(":\n");
270 torben 554 if (loc != null) {
271 torben 561 message.append( getString(stationlist_obtainedby) ).append( loc.getProvider() ).append("\n");
272     message.append( getString(stationlist_accuracy) ).append( (int)loc.getAccuracy()).append("m\n");
273 torben 564 message.append( getString(stationlist_latitude) ).append( (float)loc.getLatitude()).append("\n");
274     message.append( getString(stationlist_longitude) ).append( (float)loc.getLongitude() ).append("\n");
275 torben 554 } else {
276 torben 561 message.append( getString(stationlist_nolocation) );
277 torben 556 }
278    
279 torben 906 MessageBox.showMessage(this, message.toString(), false);
280 torben 371 break;
281 torben 368 default:
282     retval = super.onOptionsItemSelected(item);
283     }
284    
285     return retval;
286     }
287 torben 433
288    
289 torben 368
290     @Override
291 torben 433 public boolean onContextItemSelected(MenuItem item) {
292     contextMenu.onContextItemSelected(item);
293     return true;
294    
295    
296     }
297 torben 556
298     public void showMessageAndClose(String message) {
299     AlertDialog.Builder builder = new AlertDialog.Builder(this);
300     builder.setMessage(message)
301     .setCancelable(false)
302     .setPositiveButton("OK", new DialogInterface.OnClickListener() {
303     public void onClick(DialogInterface dialog, int id) {
304     dialog.dismiss();
305     StationList.this.finish();
306     }
307     })
308     .show();
309     }
310 torben 433
311    
312    
313    
314     @Override
315 torben 237 protected Dialog onCreateDialog(int id) {
316     switch (id) {
317     case DLG_PROGRESS:
318     ProgressDialog dlg = new ProgressDialog(this);
319 torben 561 dlg.setMessage( getString(stationlist_waitforlocation) );
320 torben 237 dlg.setCancelable(false);
321 torben 336 return dlg;
322 torben 381 case DLG_STATIONNAME:
323     LayoutInflater factory = LayoutInflater.from(this);
324     final View rootView = factory.inflate(R.layout.textinput, null);
325    
326    
327     AlertDialog.Builder builder = new AlertDialog.Builder(this);
328    
329 torben 561 builder.setTitle( getString(stationlist_stationsearch) );
330 torben 381 builder.setView(rootView);
331     builder.setCancelable(true);
332 torben 561 builder.setPositiveButton( getString(generic_search), new DialogInterface.OnClickListener() {
333 torben 381 public void onClick(DialogInterface dialog, int which) {
334     EditText et = (EditText) rootView.findViewById(R.id.EditText);
335     dialog.dismiss();
336 torben 713 String search = et.getText().toString().trim();
337     if (search.length() >= 2) {
338     startNameSearch(search);
339 torben 381 } else {
340 torben 561 showMessageAndClose( getString(stationlist_twocharmin) );
341 torben 381 }
342     }
343     });
344 torben 561 builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
345 torben 381 public void onClick(DialogInterface dialog, int which) {
346     dialog.dismiss();
347 torben 555 StationList.this.finish(); // Close this Activity
348 torben 381 }
349     });
350     return builder.create();
351    
352 torben 237 default:
353     return super.onCreateDialog(id);
354     }
355    
356     }
357    
358    
359     @Override
360     protected void onPrepareDialog(int id, Dialog dialog) {
361     super.onPrepareDialog(id, dialog);
362     switch (id) {
363     case DLG_PROGRESS:
364     this.dialog = (ProgressDialog) dialog;
365 torben 336 if (!dialogMessage.equals("")) {
366     this.dialog.setMessage(dialogMessage);
367     dialogMessage = "";
368     }
369 torben 237 break;
370     }
371     }
372 torben 381
373     @Override
374     protected void onListItemClick(ListView l, View v, int position, long id) {
375     super.onListItemClick(l, v, position, id);
376    
377     StationBean station = stations.get(position);
378    
379 torben 731 if (isLaunchedforShortcut == true) {
380     Intent i = new Intent();
381     i.putExtra("station", station);
382     setResult(Activity.RESULT_OK, i);
383     finish();
384     } else {
385     Intent intent = new Intent(this, DepartureList.class);
386     intent.putExtra("stationbean", station);
387     startActivity(intent);
388     }
389 torben 381 }
390    
391     /////////////////////////////////////////////////////////////
392     //
393    
394 torben 237 public void startLookup() {
395 torben 561 isRunning = true;
396     dialogMessage = getString( stationlist_waitforlocation );
397 torben 983 showDialog(DLG_PROGRESS);//TODO:showDialogSafe(DLG_PROGRESS);
398 torben 237
399 torben 482 locationLookup.locateStations();
400 torben 948 stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, GPS_TIMEOUT_MS);
401 torben 237 }
402 torben 381
403     void startNameSearch(String name) {
404 torben 561 dialogMessage = getString( stationlist_findbyname );
405 torben 983 showDialog(DLG_PROGRESS);//TODO:showDialogSafe(DLG_PROGRESS);
406 torben 237
407 torben 440 findStationsTask = new FindStationsTask();
408 torben 579 findStationsTask.searchByName(name);
409 torben 440 findStationsTask.execute();
410 torben 381
411     }
412 torben 433
413     public void startFavoriteLookup() {
414    
415 torben 440 if (favorites.size() > 0) {
416 torben 561 dialogMessage = getString( stationlist_loadfavorites );
417 torben 983 showDialog(DLG_PROGRESS);//TODO:showDialogSafe(DLG_PROGRESS);
418 torben 237
419 torben 440 findStationsTask = new FindStationsTask();
420 torben 579 findStationsTask.searchByIds( favorites.toString() );
421 torben 440 findStationsTask.execute();
422 torben 433 } else {
423 torben 561 showMessageAndClose( getString( stationlist_nofavorites ) );
424 torben 433 }
425     }
426 torben 381
427 torben 433
428 torben 381
429     void startLocatorTask()
430     {
431 torben 561 dialogMessage = getString( stationlist_findingnearby );
432 torben 983 showDialog(DLG_PROGRESS);//TODO:showDialogSafe(DLG_PROGRESS);
433 torben 381
434 torben 440 findStationsTask = new FindStationsTask();
435 torben 482 findStationsTask.searchByLocation( locationLookup.getLocation() );
436 torben 440 findStationsTask.execute();
437 torben 381 }
438    
439    
440     ////////////////////////////////////////////////////////////////////////////
441     // Inner classes
442    
443     class StationsFetchedHandler extends Handler {
444 torben 237 @Override
445     public void handleMessage(Message msg) {
446 torben 336
447 torben 237 switch (msg.what) {
448     case GOTLOCATION:
449 torben 983 dismissDialog(DLG_PROGRESS);//TODO:dismissDialogSafe(DLG_PROGRESS);
450 torben 336
451     startLocatorTask();
452 torben 482 location = GeoPair.fromLocation( locationLookup.getLocation() );
453 torben 336
454 torben 237 break;
455 torben 319
456 torben 237 case NOPROVIDER:
457 torben 983 dismissDialog(DLG_PROGRESS);//TODO:dismissDialogSafe(DLG_PROGRESS);
458 torben 906 MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider), true );
459     //StationList.this.finish();
460 torben 237 break;
461 torben 336 case LOCATIONFIXTIMEOUT:
462 torben 237 if (isRunning) {
463 torben 482 locationLookup.stopSearch();
464     if (locationLookup.hasLocation()) {
465 torben 336 stationsFetched.sendEmptyMessage( GOTLOCATION );
466     } else {
467 torben 983 dismissDialog(DLG_PROGRESS);//TODO:dismissDialogSafe(DLG_PROGRESS);
468 torben 336
469     AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);
470 torben 561 builder.setMessage( getString( stationlist_gpstimeout) );
471 torben 336 builder.setCancelable(true);
472 torben 561 builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
473 torben 336 public void onClick(DialogInterface dialog, int id) {
474     dialog.dismiss();
475     startLookup();
476    
477     }
478     });
479 torben 561 builder.setNegativeButton( getString(generic_cancel), new DialogInterface.OnClickListener() {
480 torben 336 public void onClick(DialogInterface dialog, int id) {
481     dialog.dismiss();
482     }
483 torben 701 });
484 torben 983 builder.show();//TODO:builderShowSafe(builder);
485 torben 336
486 torben 285 }
487 torben 237 }
488     break;
489     }
490     isRunning = false;
491     }
492     };
493 torben 381
494 torben 237
495 torben 440 class FindStationsTask extends AsyncTask<Void,Void,Void> {
496 torben 336
497 torben 381 LookupMethod method = LookupMethod.MethodNone;
498     boolean success;
499     String name;
500     Location loc;
501 torben 433 String ids;
502 torben 237
503 torben 579 public void searchByName(String n) {
504 torben 317
505 torben 381 method = LookupMethod.ByName;
506     name = n;
507 torben 317 }
508    
509 torben 381 public void searchByLocation(Location l) {
510     method = LookupMethod.ByLocation;
511     loc = l;
512     }
513    
514 torben 579 public void searchByIds(String id) {
515 torben 433
516     method = LookupMethod.ByList;
517     ids = id;
518     }
519    
520 torben 241 @Override
521     protected void onPreExecute() {
522 torben 258
523 torben 381 if (method.equals(LookupMethod.MethodNone))
524     throw new RuntimeException("Method not set");
525 torben 241 super.onPreExecute();
526     }
527    
528     @Override
529     protected Void doInBackground(Void... params) {
530 torben 473
531     switch (method) {
532     case ByLocation:
533 torben 381 success = stationProvider.lookupStations(loc);
534 torben 473 break;
535     case ByName:
536 torben 433 success = stationProvider.lookupStationsByName(name);
537 torben 473 break;
538     case ByList:
539 torben 433 success = stationProvider.lookupStationsByIds(ids);
540 torben 473 break;
541     default:
542     success = false; // not possible
543     }
544 torben 433
545 torben 473
546 torben 241 return null;
547     }
548    
549     @Override
550     protected void onPostExecute(Void result) {
551     super.onPostExecute(result);
552 torben 983 dialog.dismiss();//TODO:dismissDialogSafe(dialog);
553 torben 319
554 torben 473
555 torben 319 if (success) {
556 torben 566 if (stationProvider.getStations().size() == 0) {
557     showMessageAndClose(getString(stationlist_nostations));
558     }
559 torben 319 stations = stationProvider.getStations();
560 torben 917
561     StationList.this.getListView().invalidateViews();
562 torben 481 adapter.setStations( stations );
563 torben 319
564 torben 917
565 torben 319 } else { //communication or parse errors
566 torben 336 AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);
567 torben 844 builder.setMessage(getString(stationlist_fetcherror));
568 torben 336 builder.setCancelable(true);
569 torben 561 builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
570 torben 336 public void onClick(DialogInterface dialog, int id) {
571     dialog.dismiss();
572    
573 torben 652 Runnable runner = null;
574     switch (method) {
575     case ByLocation:
576     runner = new Runnable() {
577     @Override
578     public void run() {
579     startLocatorTask();
580     }
581     };
582     break;
583     case ByName:
584     runner = new Runnable() {
585     @Override
586     public void run() {
587     startNameSearch( FindStationsTask.this.name );
588     }
589     };
590     break;
591     case ByList:
592     runner = new Runnable() {
593     @Override
594     public void run() {
595     startFavoriteLookup();
596     }
597     };
598     break;
599     }
600    
601     stationsFetched.post( runner );
602 torben 336 }
603     });
604 torben 561 builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
605 torben 336 public void onClick(DialogInterface dialog, int id) {
606     dialog.dismiss();
607 torben 843 StationList.this.finish();
608 torben 336 }
609 torben 701 });
610    
611 torben 983 builder.show();//TODO:builderShowSafe(builder);
612 torben 319 }
613 torben 241 }
614     }
615 torben 433
616    
617     class FavoritesMenu implements OnCreateContextMenuListener {
618     private final static int FAVORITES_ADD = 9001;
619     private final static int FAVORITES_REMOVE = 9002;
620    
621     private int selectedPosition;
622    
623    
624     @Override
625     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
626    
627     AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
628     selectedPosition = info.position;
629     int stationID = stations.get(selectedPosition).getId();
630    
631 torben 441 if (!favorites.contains(stationID)) {
632 torben 561 menu.add(0, FAVORITES_ADD, 0, getString(stationlist_addfavorite) );
633 torben 433 } else {
634 torben 563 menu.add(0, FAVORITES_REMOVE, 0, getString(stationlist_removefavorite) );
635 torben 433 }
636    
637     }
638    
639     public void onContextItemSelected(MenuItem item) {
640     StationBean sb = stations.get(selectedPosition);
641    
642     int stationID = sb.getId();
643     if (item.getItemId() == FAVORITES_ADD) {
644     favorites.add(stationID);
645 torben 561 Toast.makeText(StationList.this, getString(stationlist_stationadded), Toast.LENGTH_SHORT).show();
646 torben 433 } else {
647 torben 473
648 torben 433 favorites.remove(stationID);
649 torben 561 Toast.makeText(StationList.this, getString(stationlist_stationremoved), Toast.LENGTH_SHORT).show();
650 torben 473
651 torben 481
652     if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) {
653 torben 473 stations.remove(selectedPosition);
654     adapter.notifyDataSetChanged();
655     }
656 torben 433 }
657 torben 435 Editor ed = prefs.edit();
658     ed.putString("favorites", favorites.toString());
659     ed.commit();
660 torben 433 }
661     }
662 torben 237 }

  ViewVC Help
Powered by ViewVC 1.1.20