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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.20