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

  ViewVC Help
Powered by ViewVC 1.1.20