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

  ViewVC Help
Powered by ViewVC 1.1.20