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

  ViewVC Help
Powered by ViewVC 1.1.20