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

  ViewVC Help
Powered by ViewVC 1.1.20