/[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 983 - (show 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 package dk.thoerup.traininfo;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6
7 import android.app.Activity;
8 import android.app.AlertDialog;
9 import android.app.Dialog;
10 import android.app.ListActivity;
11 import android.app.ProgressDialog;
12 import android.content.DialogInterface;
13 import android.content.Intent;
14 import android.content.SharedPreferences;
15 import android.content.SharedPreferences.Editor;
16 import android.location.Location;
17 import android.os.AsyncTask;
18 import android.os.Bundle;
19 import android.os.Handler;
20 import android.os.Message;
21
22 import android.util.Log;
23 import android.view.ContextMenu;
24 import android.view.LayoutInflater;
25 import android.view.Menu;
26 import android.view.MenuItem;
27 import android.view.View;
28 import android.view.ContextMenu.ContextMenuInfo;
29 import android.view.View.OnCreateContextMenuListener;
30 import android.widget.AdapterView;
31 import android.widget.EditText;
32 import android.widget.ListView;
33 import android.widget.Toast;
34 import dk.thoerup.traininfo.provider.ProviderFactory;
35 import dk.thoerup.traininfo.provider.StationProvider;
36 import dk.thoerup.traininfo.stationmap.GeoPair;
37 import dk.thoerup.traininfo.stationmap.StationMapView;
38 import dk.thoerup.traininfo.util.IntSet;
39 import dk.thoerup.traininfo.util.MessageBox;
40
41 import static dk.thoerup.traininfo.R.string.*;
42
43 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
49 public static final int OPTIONS_MAP = 2003;
50 public static final int OPTIONS_GPSINFO = 2004;
51
52 public static final int DLG_PROGRESS = 3001;
53 public static final int DLG_STATIONNAME = 3002;
54
55
56 public static final int GPS_TIMEOUT_MS = 17500; //how long are we willing to wait for gps fix -in milliseconds
57
58
59 static enum LookupMethod {
60 ByLocation,
61 ByName,
62 ByList,
63 MethodNone
64 }
65
66
67 String dialogMessage = "";
68 ProgressDialog dialog;
69 LocationLookup locationLookup = null;
70 FindStationsTask findStationsTask;
71 StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
72
73 GeoPair location = new GeoPair();
74
75 boolean isLaunchedforShortcut;
76 boolean isRunning = false;
77 List<StationBean> stations = new ArrayList<StationBean>();
78
79 StationProvider stationProvider = ProviderFactory.getStationProvider();
80
81 StationListAdapter adapter = null;
82
83 FavoritesMenu contextMenu = new FavoritesMenu();
84 IntSet favorites = new IntSet();
85
86 WelcomeScreen.ListType listType;
87 SharedPreferences prefs;
88
89 ///////////////////////////////////////////////////////////////////////////////////////////
90 //Activity call backs
91
92 @SuppressWarnings("unchecked")
93 @Override
94 public void onCreate(Bundle savedInstanceState) {
95 super.onCreate(savedInstanceState);
96 setContentView(R.layout.stationlist);
97
98
99 adapter = new StationListAdapter(this);
100 setListAdapter(adapter);
101
102 ListView lv = getListView();
103 lv.setOnCreateContextMenuListener(contextMenu);
104
105 locationLookup = new LocationLookup(this, stationsFetched);
106
107
108 prefs = getSharedPreferences("TrainStation", 0);
109 String favoriteString = prefs.getString("favorites", "");
110 if (! favoriteString.equals("") ) {
111 favorites.fromString(favoriteString);
112 }
113
114 listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type");
115 setTitle();
116
117 isLaunchedforShortcut = getIntent().getBooleanExtra("shortcut", false);
118
119 if (savedInstanceState == null) {
120
121
122 switch (listType) {
123 case ListNearest:
124 startLookup();
125 break;
126 case ListSearch:
127 showDialog(DLG_STATIONNAME); //TODO: this.showDialogSafe(DLG_STATIONNAME);
128 break;
129 case ListFavorites:
130 startFavoriteLookup();
131 break;
132 default:
133 // Not possible !?!
134 }
135
136 } else {
137 stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");
138 adapter.setStations(stations);
139 location = (GeoPair) savedInstanceState.getSerializable("location");
140 }
141
142 }
143
144
145 @Override
146 protected void onDestroy() {
147 super.onDestroy();
148
149 if (findStationsTask != null) {
150 findStationsTask.cancel(true);
151 }
152 if (locationLookup != null) {
153 locationLookup.stopSearch();
154 }
155 isRunning = false;
156 }
157
158
159 protected void setTitle() {
160 String dialogTitle = getResources().getString(app_name);
161 switch (listType) {
162 case ListNearest:
163 dialogTitle += " - " + getString(stationlist_nearbystations);
164 break;
165 case ListSearch:
166 dialogTitle += " - " + getString(stationlist_search);
167 break;
168 case ListFavorites:
169 dialogTitle += " - " + getString(stationlist_favorites);
170 break;
171 default:
172 dialogTitle = "";//not possible
173 }
174
175 setTitle(dialogTitle);
176
177 }
178
179
180 /* 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 /*
187 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 public void dismissDialogSafe(Dialog dlg) {
203 try {
204 dlg.dismiss();
205 } catch (Exception e) {
206 Log.e("StationList", "dismissDialog failed", e);
207 }
208 }
209
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 }*/
218
219 /* EOF rude and ugly dialog hack */
220
221
222
223 @Override
224 public void onSaveInstanceState(Bundle outState)
225 {
226 if (dialog != null && dialog.isShowing())
227 dialog.dismiss();
228 outState.putSerializable("stations", (ArrayList<StationBean>) stations);
229 outState.putSerializable("location", location);
230
231 }
232
233
234
235 @Override
236 public boolean onCreateOptionsMenu(Menu menu) {
237 MenuItem item;
238
239 item = menu.add(0, OPTIONS_MAP, 0, getString(stationlist_stationmap));
240 item.setIcon(android.R.drawable.ic_menu_mapmode);
241
242 item = menu.add(0, OPTIONS_GPSINFO, 0, getString(stationlist_gpsinfo));
243 item.setIcon(android.R.drawable.ic_menu_mapmode);
244
245 return true;
246 }
247
248 @Override
249 public boolean onOptionsItemSelected(MenuItem item) {
250 boolean retval = true;
251
252 //TODO: Cleanup
253 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 stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
261 }
262
263 intent.putExtra("stations", stationPoints);
264
265 startActivity(intent);
266 break;
267 case OPTIONS_GPSINFO:
268 Location loc = locationLookup.getLocation();
269 StringBuffer message = new StringBuffer();
270 message.append( getString(stationlist_locationinfo) ).append(":\n");
271 if (loc != null) {
272 message.append( getString(stationlist_obtainedby) ).append( loc.getProvider() ).append("\n");
273 message.append( getString(stationlist_accuracy) ).append( (int)loc.getAccuracy()).append("m\n");
274 message.append( getString(stationlist_latitude) ).append( (float)loc.getLatitude()).append("\n");
275 message.append( getString(stationlist_longitude) ).append( (float)loc.getLongitude() ).append("\n");
276 } else {
277 message.append( getString(stationlist_nolocation) );
278 }
279
280 MessageBox.showMessage(this, message.toString(), false);
281 break;
282 default:
283 retval = super.onOptionsItemSelected(item);
284 }
285
286 return retval;
287 }
288
289
290
291 @Override
292 public boolean onContextItemSelected(MenuItem item) {
293 contextMenu.onContextItemSelected(item);
294 return true;
295
296
297 }
298
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
312
313
314
315 @Override
316 protected Dialog onCreateDialog(int id) {
317 switch (id) {
318 case DLG_PROGRESS:
319 ProgressDialog dlg = new ProgressDialog(this);
320 dlg.setMessage( getString(stationlist_waitforlocation) );
321 dlg.setCancelable(false);
322 return dlg;
323 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 builder.setTitle( getString(stationlist_stationsearch) );
331 builder.setView(rootView);
332 builder.setCancelable(true);
333 builder.setPositiveButton( getString(generic_search), new DialogInterface.OnClickListener() {
334 public void onClick(DialogInterface dialog, int which) {
335 EditText et = (EditText) rootView.findViewById(R.id.EditText);
336 dialog.dismiss();
337 String search = et.getText().toString().trim();
338 if (search.length() >= 2) {
339 startNameSearch(search);
340 } else {
341 showMessageAndClose( getString(stationlist_twocharmin) );
342 }
343 }
344 });
345 builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
346 public void onClick(DialogInterface dialog, int which) {
347 dialog.dismiss();
348 StationList.this.finish(); // Close this Activity
349 }
350 });
351 return builder.create();
352
353 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 if (!dialogMessage.equals("")) {
367 this.dialog.setMessage(dialogMessage);
368 dialogMessage = "";
369 }
370 break;
371 }
372 }
373
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 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 }
391
392 /////////////////////////////////////////////////////////////
393 //
394
395 public void startLookup() {
396 isRunning = true;
397 dialogMessage = getString( stationlist_waitforlocation );
398 showDialog(DLG_PROGRESS);//TODO:showDialogSafe(DLG_PROGRESS);
399
400 locationLookup.locateStations();
401 stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, GPS_TIMEOUT_MS);
402 }
403
404 void startNameSearch(String name) {
405 dialogMessage = getString( stationlist_findbyname );
406 showDialog(DLG_PROGRESS);//TODO:showDialogSafe(DLG_PROGRESS);
407
408 findStationsTask = new FindStationsTask();
409 findStationsTask.searchByName(name);
410 findStationsTask.execute();
411
412 }
413
414 public void startFavoriteLookup() {
415
416 if (favorites.size() > 0) {
417 dialogMessage = getString( stationlist_loadfavorites );
418 showDialog(DLG_PROGRESS);//TODO:showDialogSafe(DLG_PROGRESS);
419
420 findStationsTask = new FindStationsTask();
421 findStationsTask.searchByIds( favorites.toString() );
422 findStationsTask.execute();
423 } else {
424 showMessageAndClose( getString( stationlist_nofavorites ) );
425 }
426 }
427
428
429
430 void startLocatorTask()
431 {
432 dialogMessage = getString( stationlist_findingnearby );
433 showDialog(DLG_PROGRESS);//TODO:showDialogSafe(DLG_PROGRESS);
434
435 findStationsTask = new FindStationsTask();
436 findStationsTask.searchByLocation( locationLookup.getLocation() );
437 findStationsTask.execute();
438 }
439
440
441 ////////////////////////////////////////////////////////////////////////////
442 // Inner classes
443
444 class StationsFetchedHandler extends Handler {
445 @Override
446 public void handleMessage(Message msg) {
447
448 switch (msg.what) {
449 case GOTLOCATION:
450 dismissDialog(DLG_PROGRESS);//TODO:dismissDialogSafe(DLG_PROGRESS);
451
452 startLocatorTask();
453 location = GeoPair.fromLocation( locationLookup.getLocation() );
454
455 break;
456
457 case NOPROVIDER:
458 dismissDialog(DLG_PROGRESS);//TODO:dismissDialogSafe(DLG_PROGRESS);
459 MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider), true );
460 //StationList.this.finish();
461 break;
462 case LOCATIONFIXTIMEOUT:
463 if (isRunning) {
464 locationLookup.stopSearch();
465 if (locationLookup.hasLocation()) {
466 stationsFetched.sendEmptyMessage( GOTLOCATION );
467 } else {
468 dismissDialog(DLG_PROGRESS);//TODO:dismissDialogSafe(DLG_PROGRESS);
469
470 AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);
471 builder.setMessage( getString( stationlist_gpstimeout) );
472 builder.setCancelable(true);
473 builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
474 public void onClick(DialogInterface dialog, int id) {
475 dialog.dismiss();
476 startLookup();
477
478 }
479 });
480 builder.setNegativeButton( getString(generic_cancel), new DialogInterface.OnClickListener() {
481 public void onClick(DialogInterface dialog, int id) {
482 dialog.dismiss();
483 }
484 });
485 builder.show();//TODO:builderShowSafe(builder);
486
487 }
488 }
489 break;
490 }
491 isRunning = false;
492 }
493 };
494
495
496 class FindStationsTask extends AsyncTask<Void,Void,Void> {
497
498 LookupMethod method = LookupMethod.MethodNone;
499 boolean success;
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 success = stationProvider.lookupStations(loc);
535 break;
536 case ByName:
537 success = stationProvider.lookupStationsByName(name);
538 break;
539 case ByList:
540 success = stationProvider.lookupStationsByIds(ids);
541 break;
542 default:
543 success = false; // 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();//TODO:dismissDialogSafe(dialog);
554
555
556 if (success) {
557 if (stationProvider.getStations().size() == 0) {
558 showMessageAndClose(getString(stationlist_nostations));
559 }
560 stations = stationProvider.getStations();
561
562 StationList.this.getListView().invalidateViews();
563 adapter.setStations( stations );
564
565
566 } else { //communication or parse errors
567 AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);
568 builder.setMessage(getString(stationlist_fetcherror));
569 builder.setCancelable(true);
570 builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
571 public void onClick(DialogInterface dialog, int id) {
572 dialog.dismiss();
573
574 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 }
604 });
605 builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
606 public void onClick(DialogInterface dialog, int id) {
607 dialog.dismiss();
608 StationList.this.finish();
609 }
610 });
611
612 builder.show();//TODO:builderShowSafe(builder);
613 }
614 }
615 }
616
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 if (!favorites.contains(stationID)) {
633 menu.add(0, FAVORITES_ADD, 0, getString(stationlist_addfavorite) );
634 } else {
635 menu.add(0, FAVORITES_REMOVE, 0, getString(stationlist_removefavorite) );
636 }
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 Toast.makeText(StationList.this, getString(stationlist_stationadded), Toast.LENGTH_SHORT).show();
647 } else {
648
649 favorites.remove(stationID);
650 Toast.makeText(StationList.this, getString(stationlist_stationremoved), Toast.LENGTH_SHORT).show();
651
652
653 if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) {
654 stations.remove(selectedPosition);
655 adapter.notifyDataSetChanged();
656 }
657 }
658 Editor ed = prefs.edit();
659 ed.putString("favorites", favorites.toString());
660 ed.commit();
661 }
662 }
663 }

  ViewVC Help
Powered by ViewVC 1.1.20