/[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 473 - (hide annotations) (download)
Tue Oct 27 13:39:28 2009 UTC (14 years, 7 months ago) by torben
File size: 16135 byte(s)
Completed favorites list feature !?!
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_RESCAN = 2001;
48     public static final int OPTIONS_NAMESEARCH = 2002;
49     public static final int OPTIONS_MAP = 2003;
50     public static final int OPTIONS_ABOUT = 2004;
51 torben 433 public static final int OPTIONS_FAVORITES = 2005;
52    
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 319 LocationLookup locator = null;
69 torben 440 FindStationsTask findStationsTask;
70 torben 381 StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
71 torben 237
72 torben 374 GeoPair location = new GeoPair();
73    
74 torben 258 boolean isRunning = false;
75     List<StationBean> stations = new ArrayList<StationBean>();
76    
77 torben 319 StationProvider stationProvider = ProviderFactory.getStationProvider();
78 torben 381
79     StationListAdapter adapter = null;
80 torben 258
81 torben 433 FavoritesMenu contextMenu = new FavoritesMenu();
82     IntSet favorites = new IntSet();
83    
84 torben 473 boolean showingFavorites = false;
85 torben 319
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     setContentView(R.layout.main);
96    
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 319 locator = 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 258 if (savedInstanceState == null) {
114     startLookup();
115     } else {
116     stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");
117 torben 260 adapter.setStations(stations);
118 torben 374 location = (GeoPair) savedInstanceState.getSerializable("location");
119 torben 258 }
120 torben 237 }
121 torben 371
122    
123 torben 243 @Override
124     public void onSaveInstanceState(Bundle outState)
125     {
126 torben 258 if (dialog != null && dialog.isShowing())
127 torben 243 dialog.dismiss();
128 torben 258 outState.putSerializable("stations", (ArrayList<StationBean>) stations);
129 torben 374 outState.putSerializable("location", location);
130 torben 243 }
131 torben 237
132 torben 243
133 torben 237
134     @Override
135 torben 368 public boolean onCreateOptionsMenu(Menu menu) {
136 torben 419 MenuItem item;
137    
138 torben 439 item = menu.add(0, OPTIONS_RESCAN, 0, "Nearest stations");
139 torben 419 item.setIcon(android.R.drawable.ic_menu_mylocation);
140    
141     item = menu.add(0, OPTIONS_NAMESEARCH, 0, "Search for station");
142     item.setIcon(android.R.drawable.ic_menu_search);
143    
144 torben 433 item = menu.add(0, OPTIONS_FAVORITES, 0, "Favorites");
145     item.setIcon(android.R.drawable.ic_menu_agenda);
146    
147 torben 439 item = menu.add(0, OPTIONS_MAP, 0, "Station map");
148 torben 419 item.setIcon(android.R.drawable.ic_menu_mapmode);
149    
150     item = menu.add(0, OPTIONS_ABOUT, 0, "About");
151     item.setIcon(android.R.drawable.ic_menu_info_details);
152 torben 368 return true;
153     }
154    
155     @Override
156     public boolean onOptionsItemSelected(MenuItem item) {
157 torben 381 boolean retval = true;
158    
159 torben 368
160     switch (item.getItemId()) {
161 torben 381 case OPTIONS_RESCAN:
162     startLookup();
163     break;
164     case OPTIONS_NAMESEARCH:
165     showDialog(DLG_STATIONNAME);
166     break;
167 torben 433 case OPTIONS_FAVORITES:
168     startFavoriteLookup();
169     break;
170 torben 368 case OPTIONS_MAP:
171    
172     Intent intent = new Intent(this,StationMapView.class);
173 torben 374 intent.putExtra("userlocation", location );
174 torben 368
175     ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
176     for (StationBean st : stations ) {
177 torben 369 stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
178 torben 368 }
179    
180     intent.putExtra("stations", stationPoints);
181    
182     startActivity(intent);
183     break;
184 torben 371 case OPTIONS_ABOUT:
185     String ver = this.getResources().getString(R.string.app_version);
186    
187 torben 401 Location loc = locator.getLocation();
188 torben 371 StringBuffer message = new StringBuffer();
189     message.append("TrainInfo DK v").append(ver).append("\n");
190     message.append("By Torben Nielsen\n");
191 torben 401 message.append("\n");
192     message.append("Location info:\n");
193     message.append("-Obtained by: ").append(loc != null ? loc.getProvider() : "-").append("\n");
194     message.append("-Accuracy: ").append(loc != null ? (int)loc.getAccuracy() : "-").append("m\n");
195 torben 371
196     MessageBox.showMessage(this, message.toString());
197     break;
198 torben 368 default:
199     retval = super.onOptionsItemSelected(item);
200     }
201    
202     return retval;
203     }
204 torben 433
205    
206 torben 368
207     @Override
208 torben 433 public boolean onContextItemSelected(MenuItem item) {
209     contextMenu.onContextItemSelected(item);
210     return true;
211    
212    
213     }
214    
215    
216    
217    
218     @Override
219 torben 237 protected Dialog onCreateDialog(int id) {
220     switch (id) {
221     case DLG_PROGRESS:
222     ProgressDialog dlg = new ProgressDialog(this);
223     dlg.setMessage("Wait for location fix");
224     dlg.setCancelable(false);
225 torben 336 return dlg;
226 torben 381 case DLG_STATIONNAME:
227     LayoutInflater factory = LayoutInflater.from(this);
228     final View rootView = factory.inflate(R.layout.textinput, null);
229    
230    
231     AlertDialog.Builder builder = new AlertDialog.Builder(this);
232    
233     builder.setTitle("Station search");
234     builder.setView(rootView);
235     builder.setCancelable(true);
236     builder.setPositiveButton("Search", new DialogInterface.OnClickListener() {
237     public void onClick(DialogInterface dialog, int which) {
238     EditText et = (EditText) rootView.findViewById(R.id.EditText);
239     dialog.dismiss();
240     if (et.getText().toString().length() >= 2) {
241     startNameSearch(et.getText().toString());
242     } else {
243 torben 382 MessageBox.showMessage(StationList.this, "Two characters minimum" );
244 torben 381 }
245     }
246     });
247     builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
248     public void onClick(DialogInterface dialog, int which) {
249     dialog.dismiss();
250     }
251     });
252     return builder.create();
253    
254 torben 237 default:
255     return super.onCreateDialog(id);
256     }
257    
258     }
259    
260    
261     @Override
262     protected void onPrepareDialog(int id, Dialog dialog) {
263     super.onPrepareDialog(id, dialog);
264     switch (id) {
265     case DLG_PROGRESS:
266     this.dialog = (ProgressDialog) dialog;
267 torben 336 if (!dialogMessage.equals("")) {
268     this.dialog.setMessage(dialogMessage);
269     dialogMessage = "";
270     }
271 torben 237 break;
272     }
273     }
274 torben 381
275     @Override
276     protected void onListItemClick(ListView l, View v, int position, long id) {
277     super.onListItemClick(l, v, position, id);
278    
279     StationBean station = stations.get(position);
280 torben 237
281 torben 381 double latitude = station.getLatitude();
282     double longitude = station.getLongitude();
283    
284    
285    
286     Intent intent = new Intent(this, DepartureList.class);
287     intent.putExtra("name", station.getName());
288     intent.putExtra("distance", station.getDistance());
289     intent.putExtra("latitude", latitude);
290     intent.putExtra("longitude", longitude);
291     intent.putExtra("stationid", station.getId());
292     intent.putExtra("address", station.getAddress());
293     startActivity(intent);
294     }
295    
296     /////////////////////////////////////////////////////////////
297     //
298    
299 torben 237 public void startLookup() {
300     isRunning = true;
301 torben 381 dialogMessage = "Wait for location fix";
302 torben 237 showDialog(DLG_PROGRESS);
303    
304     locator.locateStations();
305 torben 336 stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000);
306 torben 237 }
307 torben 381
308     void startNameSearch(String name) {
309     dialogMessage = "Finding stations by name";
310     showDialog(DLG_PROGRESS);
311 torben 237
312 torben 440 findStationsTask = new FindStationsTask();
313     findStationsTask.searchByName(name, locator.getLocation());
314     findStationsTask.execute();
315 torben 381
316     }
317 torben 433
318     public void startFavoriteLookup() {
319    
320 torben 440 if (favorites.size() > 0) {
321 torben 433 dialogMessage = "Loading favorites";
322     showDialog(DLG_PROGRESS);
323 torben 237
324 torben 440 findStationsTask = new FindStationsTask();
325     findStationsTask.searchByIds(favorites.toString(), locator.getLocation());
326     findStationsTask.execute();
327 torben 433 } else {
328     MessageBox.showMessage(this, "Favorite list is empty");
329     }
330     }
331 torben 381
332 torben 433
333 torben 381
334     void startLocatorTask()
335     {
336     dialogMessage = "Finding nearby stations";
337     showDialog(DLG_PROGRESS);
338    
339 torben 440 findStationsTask = new FindStationsTask();
340     findStationsTask.searchByLocation( locator.getLocation() );
341     findStationsTask.execute();
342 torben 381 }
343    
344    
345     String lookupAddress(double latitude, double longitude) {
346    
347     Geocoder coder = new Geocoder(this, new Locale("da"));
348     StringBuilder sb = new StringBuilder();
349     Log.i("lookupaddr", "" + latitude + "/" + longitude);
350     try {
351     List<Address> addressList = coder.getFromLocation(latitude, longitude, 1);
352     Address addr = addressList.get(0);
353    
354    
355     int max = addr.getMaxAddressLineIndex();
356     for (int i=0; i<max; i++) {
357     if (i>0)
358     sb.append(", ");
359    
360     sb.append(addr.getAddressLine(i));
361     }
362    
363    
364     } catch (Exception e) {
365     Log.e("DepartureList", "geocoder failed", e);
366     }
367    
368     return sb.toString();
369     }
370    
371    
372     ////////////////////////////////////////////////////////////////////////////
373     // Inner classes
374    
375     class StationsFetchedHandler extends Handler {
376 torben 237 @Override
377     public void handleMessage(Message msg) {
378 torben 336
379 torben 237 switch (msg.what) {
380     case GOTLOCATION:
381 torben 336 dismissDialog(DLG_PROGRESS);
382    
383     startLocatorTask();
384 torben 374 location = GeoPair.fromLocation( locator.getLocation() );
385 torben 336
386 torben 237 break;
387 torben 319
388 torben 237 case NOPROVIDER:
389 torben 336 dismissDialog(DLG_PROGRESS);
390     MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps.");
391 torben 237 break;
392 torben 336 case LOCATIONFIXTIMEOUT:
393 torben 237 if (isRunning) {
394 torben 336 locator.stopSearch();
395 torben 285 if (locator.hasLocation()) {
396 torben 336 stationsFetched.sendEmptyMessage( GOTLOCATION );
397     } else {
398     dismissDialog(DLG_PROGRESS);
399    
400     AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);
401 torben 420 builder.setMessage("Location fix timed out");
402 torben 336 builder.setCancelable(true);
403     builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
404     public void onClick(DialogInterface dialog, int id) {
405     dialog.dismiss();
406     startLookup();
407    
408     }
409     });
410     builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
411     public void onClick(DialogInterface dialog, int id) {
412     dialog.dismiss();
413     }
414     });
415     builder.show();
416    
417 torben 285 }
418 torben 237 }
419     break;
420     }
421     isRunning = false;
422     }
423     };
424 torben 381
425 torben 237
426 torben 440 class FindStationsTask extends AsyncTask<Void,Void,Void> {
427 torben 336
428 torben 381 LookupMethod method = LookupMethod.MethodNone;
429     boolean success;
430     String name;
431     Location loc;
432 torben 433 String ids;
433 torben 237
434 torben 381 public void searchByName(String n, Location l) {
435 torben 317
436 torben 381 method = LookupMethod.ByName;
437     loc = l;
438     name = n;
439 torben 317 }
440    
441 torben 381 public void searchByLocation(Location l) {
442     method = LookupMethod.ByLocation;
443     loc = l;
444     }
445    
446 torben 433 public void searchByIds(String id, Location l) {
447    
448     method = LookupMethod.ByList;
449     loc = l;
450     ids = id;
451     }
452    
453 torben 241 @Override
454     protected void onPreExecute() {
455 torben 258
456 torben 381 if (method.equals(LookupMethod.MethodNone))
457     throw new RuntimeException("Method not set");
458 torben 241 super.onPreExecute();
459     }
460    
461     @Override
462     protected Void doInBackground(Void... params) {
463 torben 473
464     switch (method) {
465     case ByLocation:
466 torben 381 success = stationProvider.lookupStations(loc);
467 torben 473 break;
468     case ByName:
469 torben 433 success = stationProvider.lookupStationsByName(name);
470 torben 473 break;
471     case ByList:
472 torben 433 success = stationProvider.lookupStationsByIds(ids);
473 torben 473 break;
474     default:
475     success = false; // not possible
476     }
477 torben 433
478 torben 473
479 torben 381 Location dummy = new Location("gps");
480 torben 319 List<StationBean> stations = stationProvider.getStations();
481 torben 381
482     for (StationBean station : stations) {
483 torben 317 String addr = lookupAddress(station.getLatitude(), station.getLongitude());
484     station.setAddress(addr);
485 torben 381
486 torben 433 if (method.equals(LookupMethod.ByName) || method.equals(LookupMethod.ByList)) {
487 torben 381 dummy.setLatitude(station.getLatitude());
488     dummy.setLongitude(station.getLongitude());
489     station.setDistance( (int)loc.distanceTo(dummy) );
490     }
491     }
492 torben 317
493 torben 241 return null;
494     }
495    
496     @Override
497     protected void onPostExecute(Void result) {
498     super.onPostExecute(result);
499 torben 319 dialog.dismiss();
500    
501 torben 473 //set title
502     String title;
503     switch (method) {
504     case ByLocation:
505     title = "Traininfo DK - Nearby stations";
506     break;
507     case ByName:
508     title = "Traininfo DK - Search";
509     break;
510     case ByList:
511     title = "Traininfo DK - Favorites";
512     break;
513     default:
514     title = "";//not possible
515     }
516    
517     StationList.this.setTitle(title);
518     //set title end
519    
520 torben 319 if (success) {
521     if (stationProvider.getStations().size() == 0)
522 torben 336 MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?!
523 torben 319 stations = stationProvider.getStations();
524 torben 473 adapter.setStations( stations );
525 torben 319
526 torben 473 showingFavorites = method.equals(LookupMethod.ByList);
527    
528 torben 319 } 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     if (showingFavorites) {
590     stations.remove(selectedPosition);
591     adapter.notifyDataSetChanged();
592     }
593 torben 433 }
594 torben 435 Editor ed = prefs.edit();
595     ed.putString("favorites", favorites.toString());
596     ed.commit();
597 torben 433 }
598     }
599 torben 237 }

  ViewVC Help
Powered by ViewVC 1.1.20