/[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 489 - (hide annotations) (download)
Thu Oct 29 14:20:16 2009 UTC (14 years, 7 months ago) by torben
File size: 15785 byte(s)
Let the MylocationOverlay control where the map should be centered
1 torben 237 package dk.thoerup.traininfo;
2    
3 torben 258 import java.util.ArrayList;
4     import java.util.List;
5 torben 294 import java.util.Locale;
6 torben 258
7 torben 336 import android.app.AlertDialog;
8 torben 237 import android.app.Dialog;
9     import android.app.ListActivity;
10     import android.app.ProgressDialog;
11 torben 336 import android.content.DialogInterface;
12 torben 237 import android.content.Intent;
13 torben 433 import android.content.SharedPreferences;
14 torben 435 import android.content.SharedPreferences.Editor;
15 torben 294 import android.location.Address;
16     import android.location.Geocoder;
17 torben 319 import android.location.Location;
18 torben 241 import android.os.AsyncTask;
19 torben 237 import android.os.Bundle;
20     import android.os.Handler;
21     import android.os.Message;
22 torben 294 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 336 public class StationList extends ListActivity {
42     public static final int GOTLOCATION = 1001;
43     public static final int GOTSTATIONLIST = 1002;
44     public static final int NOPROVIDER = 1003;
45     public static final int LOCATIONFIXTIMEOUT = 1004;
46 torben 368
47 torben 381 public static final int OPTIONS_MAP = 2003;
48 torben 481 public static final int OPTIONS_GPSINFO = 2004;
49    
50 torben 433
51 torben 336
52 torben 237
53 torben 381 public static final int DLG_PROGRESS = 3001;
54     public static final int DLG_STATIONNAME = 3002;
55 torben 237
56 torben 440 static enum LookupMethod {
57     ByLocation,
58     ByName,
59     ByList,
60     MethodNone
61     }
62    
63    
64 torben 336 String dialogMessage = "";
65 torben 237 ProgressDialog dialog;
66 torben 482 LocationLookup locationLookup = null;
67 torben 440 FindStationsTask findStationsTask;
68 torben 381 StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
69 torben 237
70 torben 374 GeoPair location = new GeoPair();
71    
72 torben 258 boolean isRunning = false;
73     List<StationBean> stations = new ArrayList<StationBean>();
74    
75 torben 319 StationProvider stationProvider = ProviderFactory.getStationProvider();
76 torben 381
77     StationListAdapter adapter = null;
78 torben 258
79 torben 433 FavoritesMenu contextMenu = new FavoritesMenu();
80     IntSet favorites = new IntSet();
81 torben 481
82     WelcomeScreen.ListType listType;
83 torben 433 SharedPreferences prefs;
84    
85 torben 381 ///////////////////////////////////////////////////////////////////////////////////////////
86     //Activity call backs
87    
88 torben 258 @SuppressWarnings("unchecked")
89 torben 237 @Override
90     public void onCreate(Bundle savedInstanceState) {
91     super.onCreate(savedInstanceState);
92 torben 481 setContentView(R.layout.stationlist);
93 torben 237
94 torben 241
95 torben 237 adapter = new StationListAdapter(this);
96     setListAdapter(adapter);
97    
98 torben 433 ListView lv = getListView();
99     lv.setOnCreateContextMenuListener(contextMenu);
100    
101 torben 482 locationLookup = new LocationLookup(this, stationsFetched);
102 torben 433
103    
104     prefs = getSharedPreferences("TrainStation", 0);
105     String favoriteString = prefs.getString("favorites", "");
106     if (! favoriteString.equals("") ) {
107     favorites.fromString(favoriteString);
108     }
109    
110 torben 482 listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type");
111     setTitle();
112    
113 torben 258 if (savedInstanceState == null) {
114 torben 482
115    
116 torben 481 switch (listType) {
117     case ListNearest:
118     startLookup();
119     break;
120     case ListSearch:
121     this.showDialog(DLG_STATIONNAME);
122     break;
123     case ListFavorites:
124     startFavoriteLookup();
125     break;
126     default:
127     // Not possible !?!
128     }
129    
130 torben 258 } else {
131     stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");
132 torben 260 adapter.setStations(stations);
133 torben 374 location = (GeoPair) savedInstanceState.getSerializable("location");
134 torben 258 }
135 torben 482
136 torben 237 }
137 torben 482 protected void setTitle() {
138 torben 484 String dialogTitle = getResources().getString(R.string.app_name);
139 torben 482 switch (listType) {
140     case ListNearest:
141 torben 484 dialogTitle += " - Nearby stations";
142 torben 482 break;
143     case ListSearch:
144 torben 484 dialogTitle += " - Search";
145 torben 482 break;
146     case ListFavorites:
147 torben 484 dialogTitle += " - Favorites";
148 torben 482 break;
149     default:
150     dialogTitle = "";//not possible
151     }
152    
153     setTitle(dialogTitle);
154     }
155    
156    
157 torben 371
158    
159 torben 243 @Override
160     public void onSaveInstanceState(Bundle outState)
161     {
162 torben 258 if (dialog != null && dialog.isShowing())
163 torben 243 dialog.dismiss();
164 torben 258 outState.putSerializable("stations", (ArrayList<StationBean>) stations);
165 torben 374 outState.putSerializable("location", location);
166 torben 482
167 torben 243 }
168 torben 237
169 torben 243
170 torben 237
171     @Override
172 torben 368 public boolean onCreateOptionsMenu(Menu menu) {
173 torben 419 MenuItem item;
174 torben 481
175 torben 439 item = menu.add(0, OPTIONS_MAP, 0, "Station map");
176 torben 419 item.setIcon(android.R.drawable.ic_menu_mapmode);
177    
178 torben 481 item = menu.add(0, OPTIONS_GPSINFO, 0, "GPS Info");
179     item.setIcon(android.R.drawable.ic_menu_mapmode);
180    
181 torben 368 return true;
182     }
183    
184     @Override
185     public boolean onOptionsItemSelected(MenuItem item) {
186 torben 381 boolean retval = true;
187    
188 torben 481 //TODO: Cleanup
189 torben 368 switch (item.getItemId()) {
190     case OPTIONS_MAP:
191    
192     Intent intent = new Intent(this,StationMapView.class);
193    
194     ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
195     for (StationBean st : stations ) {
196 torben 369 stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
197 torben 368 }
198    
199     intent.putExtra("stations", stationPoints);
200    
201     startActivity(intent);
202     break;
203 torben 481 case OPTIONS_GPSINFO:
204 torben 482 Location loc = locationLookup.getLocation();
205 torben 371 StringBuffer message = new StringBuffer();
206 torben 401 message.append("Location info:\n");
207     message.append("-Obtained by: ").append(loc != null ? loc.getProvider() : "-").append("\n");
208     message.append("-Accuracy: ").append(loc != null ? (int)loc.getAccuracy() : "-").append("m\n");
209 torben 371
210     MessageBox.showMessage(this, message.toString());
211     break;
212 torben 368 default:
213     retval = super.onOptionsItemSelected(item);
214     }
215    
216     return retval;
217     }
218 torben 433
219    
220 torben 368
221     @Override
222 torben 433 public boolean onContextItemSelected(MenuItem item) {
223     contextMenu.onContextItemSelected(item);
224     return true;
225    
226    
227     }
228    
229    
230    
231    
232     @Override
233 torben 237 protected Dialog onCreateDialog(int id) {
234     switch (id) {
235     case DLG_PROGRESS:
236     ProgressDialog dlg = new ProgressDialog(this);
237     dlg.setMessage("Wait for location fix");
238     dlg.setCancelable(false);
239 torben 336 return dlg;
240 torben 381 case DLG_STATIONNAME:
241     LayoutInflater factory = LayoutInflater.from(this);
242     final View rootView = factory.inflate(R.layout.textinput, null);
243    
244    
245     AlertDialog.Builder builder = new AlertDialog.Builder(this);
246    
247     builder.setTitle("Station search");
248     builder.setView(rootView);
249     builder.setCancelable(true);
250     builder.setPositiveButton("Search", new DialogInterface.OnClickListener() {
251     public void onClick(DialogInterface dialog, int which) {
252     EditText et = (EditText) rootView.findViewById(R.id.EditText);
253     dialog.dismiss();
254     if (et.getText().toString().length() >= 2) {
255     startNameSearch(et.getText().toString());
256     } else {
257 torben 382 MessageBox.showMessage(StationList.this, "Two characters minimum" );
258 torben 381 }
259     }
260     });
261     builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
262     public void onClick(DialogInterface dialog, int which) {
263     dialog.dismiss();
264     }
265     });
266     return builder.create();
267    
268 torben 237 default:
269     return super.onCreateDialog(id);
270     }
271    
272     }
273    
274    
275     @Override
276     protected void onPrepareDialog(int id, Dialog dialog) {
277     super.onPrepareDialog(id, dialog);
278     switch (id) {
279     case DLG_PROGRESS:
280     this.dialog = (ProgressDialog) dialog;
281 torben 336 if (!dialogMessage.equals("")) {
282     this.dialog.setMessage(dialogMessage);
283     dialogMessage = "";
284     }
285 torben 237 break;
286     }
287     }
288 torben 381
289     @Override
290     protected void onListItemClick(ListView l, View v, int position, long id) {
291     super.onListItemClick(l, v, position, id);
292    
293     StationBean station = stations.get(position);
294 torben 237
295 torben 381 double latitude = station.getLatitude();
296     double longitude = station.getLongitude();
297    
298    
299    
300     Intent intent = new Intent(this, DepartureList.class);
301     intent.putExtra("name", station.getName());
302     intent.putExtra("distance", station.getDistance());
303     intent.putExtra("latitude", latitude);
304     intent.putExtra("longitude", longitude);
305     intent.putExtra("stationid", station.getId());
306     intent.putExtra("address", station.getAddress());
307     startActivity(intent);
308     }
309    
310     /////////////////////////////////////////////////////////////
311     //
312    
313 torben 237 public void startLookup() {
314     isRunning = true;
315 torben 381 dialogMessage = "Wait for location fix";
316 torben 237 showDialog(DLG_PROGRESS);
317    
318 torben 482 locationLookup.locateStations();
319 torben 336 stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000);
320 torben 237 }
321 torben 381
322     void startNameSearch(String name) {
323     dialogMessage = "Finding stations by name";
324     showDialog(DLG_PROGRESS);
325 torben 237
326 torben 440 findStationsTask = new FindStationsTask();
327 torben 482 findStationsTask.searchByName(name, locationLookup.getLocation());
328 torben 440 findStationsTask.execute();
329 torben 381
330     }
331 torben 433
332     public void startFavoriteLookup() {
333    
334 torben 440 if (favorites.size() > 0) {
335 torben 433 dialogMessage = "Loading favorites";
336     showDialog(DLG_PROGRESS);
337 torben 237
338 torben 440 findStationsTask = new FindStationsTask();
339 torben 482 findStationsTask.searchByIds(favorites.toString(), locationLookup.getLocation());
340 torben 440 findStationsTask.execute();
341 torben 433 } else {
342     MessageBox.showMessage(this, "Favorite list is empty");
343     }
344     }
345 torben 381
346 torben 433
347 torben 381
348     void startLocatorTask()
349     {
350     dialogMessage = "Finding nearby stations";
351     showDialog(DLG_PROGRESS);
352    
353 torben 440 findStationsTask = new FindStationsTask();
354 torben 482 findStationsTask.searchByLocation( locationLookup.getLocation() );
355 torben 440 findStationsTask.execute();
356 torben 381 }
357    
358    
359     String lookupAddress(double latitude, double longitude) {
360    
361     Geocoder coder = new Geocoder(this, new Locale("da"));
362     StringBuilder sb = new StringBuilder();
363     Log.i("lookupaddr", "" + latitude + "/" + longitude);
364     try {
365     List<Address> addressList = coder.getFromLocation(latitude, longitude, 1);
366     Address addr = addressList.get(0);
367    
368    
369     int max = addr.getMaxAddressLineIndex();
370     for (int i=0; i<max; i++) {
371     if (i>0)
372     sb.append(", ");
373    
374     sb.append(addr.getAddressLine(i));
375     }
376    
377    
378     } catch (Exception e) {
379     Log.e("DepartureList", "geocoder failed", e);
380     }
381    
382     return sb.toString();
383     }
384    
385    
386     ////////////////////////////////////////////////////////////////////////////
387     // Inner classes
388    
389     class StationsFetchedHandler extends Handler {
390 torben 237 @Override
391     public void handleMessage(Message msg) {
392 torben 336
393 torben 237 switch (msg.what) {
394     case GOTLOCATION:
395 torben 336 dismissDialog(DLG_PROGRESS);
396    
397     startLocatorTask();
398 torben 482 location = GeoPair.fromLocation( locationLookup.getLocation() );
399 torben 336
400 torben 237 break;
401 torben 319
402 torben 237 case NOPROVIDER:
403 torben 336 dismissDialog(DLG_PROGRESS);
404     MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps.");
405 torben 237 break;
406 torben 336 case LOCATIONFIXTIMEOUT:
407 torben 237 if (isRunning) {
408 torben 482 locationLookup.stopSearch();
409     if (locationLookup.hasLocation()) {
410 torben 336 stationsFetched.sendEmptyMessage( GOTLOCATION );
411     } else {
412     dismissDialog(DLG_PROGRESS);
413    
414     AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);
415 torben 420 builder.setMessage("Location fix timed out");
416 torben 336 builder.setCancelable(true);
417     builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
418     public void onClick(DialogInterface dialog, int id) {
419     dialog.dismiss();
420     startLookup();
421    
422     }
423     });
424     builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
425     public void onClick(DialogInterface dialog, int id) {
426     dialog.dismiss();
427     }
428     });
429     builder.show();
430    
431 torben 285 }
432 torben 237 }
433     break;
434     }
435     isRunning = false;
436     }
437     };
438 torben 381
439 torben 237
440 torben 440 class FindStationsTask extends AsyncTask<Void,Void,Void> {
441 torben 336
442 torben 381 LookupMethod method = LookupMethod.MethodNone;
443     boolean success;
444     String name;
445     Location loc;
446 torben 433 String ids;
447 torben 237
448 torben 381 public void searchByName(String n, Location l) {
449 torben 317
450 torben 381 method = LookupMethod.ByName;
451     loc = l;
452     name = n;
453 torben 317 }
454    
455 torben 381 public void searchByLocation(Location l) {
456     method = LookupMethod.ByLocation;
457     loc = l;
458     }
459    
460 torben 433 public void searchByIds(String id, Location l) {
461    
462     method = LookupMethod.ByList;
463     loc = l;
464     ids = id;
465     }
466    
467 torben 241 @Override
468     protected void onPreExecute() {
469 torben 258
470 torben 381 if (method.equals(LookupMethod.MethodNone))
471     throw new RuntimeException("Method not set");
472 torben 241 super.onPreExecute();
473     }
474    
475     @Override
476     protected Void doInBackground(Void... params) {
477 torben 473
478     switch (method) {
479     case ByLocation:
480 torben 381 success = stationProvider.lookupStations(loc);
481 torben 473 break;
482     case ByName:
483 torben 433 success = stationProvider.lookupStationsByName(name);
484 torben 473 break;
485     case ByList:
486 torben 433 success = stationProvider.lookupStationsByIds(ids);
487 torben 473 break;
488     default:
489     success = false; // not possible
490     }
491 torben 433
492 torben 473
493 torben 381 Location dummy = new Location("gps");
494 torben 319 List<StationBean> stations = stationProvider.getStations();
495 torben 381
496     for (StationBean station : stations) {
497 torben 317 String addr = lookupAddress(station.getLatitude(), station.getLongitude());
498     station.setAddress(addr);
499 torben 381
500 torben 478
501     if (method.equals(LookupMethod.ByName) || method.equals(LookupMethod.ByList)) {
502     if (loc != null) { //only do the distance calc if we have a location
503 torben 476 dummy.setLatitude(station.getLatitude());
504     dummy.setLongitude(station.getLongitude());
505     station.setDistance( (int)loc.distanceTo(dummy) );
506 torben 478 } else {
507     station.setDistance(0);
508 torben 476 }
509 torben 381 }
510 torben 478
511 torben 381 }
512 torben 317
513 torben 241 return null;
514     }
515    
516     @Override
517     protected void onPostExecute(Void result) {
518     super.onPostExecute(result);
519 torben 319 dialog.dismiss();
520    
521 torben 473
522 torben 319 if (success) {
523     if (stationProvider.getStations().size() == 0)
524 torben 336 MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?!
525 torben 319 stations = stationProvider.getStations();
526 torben 481 adapter.setStations( stations );
527 torben 319
528     } else { //communication or parse errors
529 torben 336 AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);
530     builder.setMessage("Error on finding nearby stations");
531     builder.setCancelable(true);
532     builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
533     public void onClick(DialogInterface dialog, int id) {
534     dialog.dismiss();
535    
536     stationsFetched.post( new Runnable() {
537     @Override
538     public void run() {
539     startLocatorTask();
540     }
541     });
542     }
543     });
544     builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
545     public void onClick(DialogInterface dialog, int id) {
546     dialog.dismiss();
547     }
548     });
549     builder.show();
550 torben 319 }
551 torben 241 }
552     }
553 torben 433
554    
555     class FavoritesMenu implements OnCreateContextMenuListener {
556     private final static int FAVORITES_ADD = 9001;
557     private final static int FAVORITES_REMOVE = 9002;
558    
559     private int selectedPosition;
560    
561    
562     @Override
563     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
564    
565     AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
566     selectedPosition = info.position;
567     int stationID = stations.get(selectedPosition).getId();
568    
569 torben 441 if (!favorites.contains(stationID)) {
570 torben 433 menu.add(0, FAVORITES_ADD, 0, "Add to favorites");
571     } else {
572     menu.add(0, FAVORITES_REMOVE, 0, "Remove from favorites");
573     }
574    
575     }
576    
577     public void onContextItemSelected(MenuItem item) {
578     StationBean sb = stations.get(selectedPosition);
579    
580     int stationID = sb.getId();
581     if (item.getItemId() == FAVORITES_ADD) {
582     favorites.add(stationID);
583     Toast.makeText(StationList.this, "Station added", Toast.LENGTH_SHORT).show();
584     } else {
585 torben 473
586 torben 433 favorites.remove(stationID);
587     Toast.makeText(StationList.this, "Station removed", Toast.LENGTH_SHORT).show();
588 torben 473
589 torben 481
590     if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) {
591 torben 473 stations.remove(selectedPosition);
592     adapter.notifyDataSetChanged();
593     }
594 torben 433 }
595 torben 435 Editor ed = prefs.edit();
596     ed.putString("favorites", favorites.toString());
597     ed.commit();
598 torben 433 }
599     }
600 torben 237 }

  ViewVC Help
Powered by ViewVC 1.1.20