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

  ViewVC Help
Powered by ViewVC 1.1.20