--- android/TrainInfo/src/dk/thoerup/traininfo/StationList.java 2009/09/30 16:40:48 369 +++ android/TrainInfo/src/dk/thoerup/traininfo/StationList.java 2009/10/11 07:23:35 441 @@ -10,6 +10,8 @@ import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; import android.location.Address; import android.location.Geocoder; import android.location.Location; @@ -18,16 +20,22 @@ import android.os.Handler; import android.os.Message; import android.util.Log; +import android.view.ContextMenu; +import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; +import android.view.ContextMenu.ContextMenuInfo; +import android.view.View.OnCreateContextMenuListener; +import android.widget.AdapterView; +import android.widget.EditText; import android.widget.ListView; - - +import android.widget.Toast; import dk.thoerup.traininfo.provider.ProviderFactory; import dk.thoerup.traininfo.provider.StationProvider; import dk.thoerup.traininfo.stationmap.GeoPair; import dk.thoerup.traininfo.stationmap.StationMapView; +import dk.thoerup.traininfo.util.IntSet; import dk.thoerup.traininfo.util.MessageBox; public class StationList extends ListActivity { @@ -36,25 +44,50 @@ public static final int NOPROVIDER = 1003; public static final int LOCATIONFIXTIMEOUT = 1004; - public static final int OPTIONS_MAP = 2001; - public static final int OPTIONS_ABOUT = 2002; + public static final int OPTIONS_RESCAN = 2001; + public static final int OPTIONS_NAMESEARCH = 2002; + public static final int OPTIONS_MAP = 2003; + public static final int OPTIONS_ABOUT = 2004; + public static final int OPTIONS_FAVORITES = 2005; + - public static final int DLG_PROGRESS = 1001; + public static final int DLG_PROGRESS = 3001; + public static final int DLG_STATIONNAME = 3002; + + static enum LookupMethod { + ByLocation, + ByName, + ByList, + MethodNone + } + - /** Called when the activity is first created. */ String dialogMessage = ""; ProgressDialog dialog; LocationLookup locator = null; - LocatorTask locatorTask; + FindStationsTask findStationsTask; + StationsFetchedHandler stationsFetched = new StationsFetchedHandler(); + + GeoPair location = new GeoPair(); boolean isRunning = false; List stations = new ArrayList(); StationProvider stationProvider = ProviderFactory.getStationProvider(); + + StationListAdapter adapter = null; + FavoritesMenu contextMenu = new FavoritesMenu(); + IntSet favorites = new IntSet(); + + + + SharedPreferences prefs; + + /////////////////////////////////////////////////////////////////////////////////////////// + //Activity call backs - StationListAdapter adapter = null; @SuppressWarnings("unchecked") @Override public void onCreate(Bundle savedInstanceState) { @@ -65,42 +98,79 @@ adapter = new StationListAdapter(this); setListAdapter(adapter); + ListView lv = getListView(); + lv.setOnCreateContextMenuListener(contextMenu); + locator = new LocationLookup(this, stationsFetched); + + + prefs = getSharedPreferences("TrainStation", 0); + String favoriteString = prefs.getString("favorites", ""); + if (! favoriteString.equals("") ) { + favorites.fromString(favoriteString); + } + if (savedInstanceState == null) { startLookup(); } else { stations = (ArrayList) savedInstanceState.getSerializable("stations"); adapter.setStations(stations); + location = (GeoPair) savedInstanceState.getSerializable("location"); } } - + + @Override public void onSaveInstanceState(Bundle outState) { if (dialog != null && dialog.isShowing()) dialog.dismiss(); outState.putSerializable("stations", (ArrayList) stations); + outState.putSerializable("location", location); } @Override public boolean onCreateOptionsMenu(Menu menu) { - menu.add(0, OPTIONS_MAP, 0, "Show station map"); - menu.add(0, OPTIONS_ABOUT, 0, "About"); + MenuItem item; + + item = menu.add(0, OPTIONS_RESCAN, 0, "Nearest stations"); + item.setIcon(android.R.drawable.ic_menu_mylocation); + + item = menu.add(0, OPTIONS_NAMESEARCH, 0, "Search for station"); + item.setIcon(android.R.drawable.ic_menu_search); + + item = menu.add(0, OPTIONS_FAVORITES, 0, "Favorites"); + item.setIcon(android.R.drawable.ic_menu_agenda); + + item = menu.add(0, OPTIONS_MAP, 0, "Station map"); + item.setIcon(android.R.drawable.ic_menu_mapmode); + item = menu.add(0, OPTIONS_ABOUT, 0, "About"); + item.setIcon(android.R.drawable.ic_menu_info_details); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { - boolean retval; + boolean retval = true; + switch (item.getItemId()) { + case OPTIONS_RESCAN: + startLookup(); + break; + case OPTIONS_NAMESEARCH: + showDialog(DLG_STATIONNAME); + break; + case OPTIONS_FAVORITES: + startFavoriteLookup(); + break; case OPTIONS_MAP: Intent intent = new Intent(this,StationMapView.class); - intent.putExtra("userlocation", GeoPair.fromLocation(locator.getLocation()) ); + intent.putExtra("userlocation", location ); ArrayList stationPoints = new ArrayList(); for (StationBean st : stations ) { @@ -110,7 +180,20 @@ intent.putExtra("stations", stationPoints); startActivity(intent); - retval = true; + break; + case OPTIONS_ABOUT: + String ver = this.getResources().getString(R.string.app_version); + + Location loc = locator.getLocation(); + StringBuffer message = new StringBuffer(); + message.append("TrainInfo DK v").append(ver).append("\n"); + message.append("By Torben Nielsen\n"); + message.append("\n"); + message.append("Location info:\n"); + message.append("-Obtained by: ").append(loc != null ? loc.getProvider() : "-").append("\n"); + message.append("-Accuracy: ").append(loc != null ? (int)loc.getAccuracy() : "-").append("m\n"); + + MessageBox.showMessage(this, message.toString()); break; default: retval = super.onOptionsItemSelected(item); @@ -118,6 +201,19 @@ return retval; } + + + + @Override + public boolean onContextItemSelected(MenuItem item) { + contextMenu.onContextItemSelected(item); + return true; + + + } + + + @Override protected Dialog onCreateDialog(int id) { @@ -127,6 +223,34 @@ dlg.setMessage("Wait for location fix"); dlg.setCancelable(false); return dlg; + case DLG_STATIONNAME: + LayoutInflater factory = LayoutInflater.from(this); + final View rootView = factory.inflate(R.layout.textinput, null); + + + AlertDialog.Builder builder = new AlertDialog.Builder(this); + + builder.setTitle("Station search"); + builder.setView(rootView); + builder.setCancelable(true); + builder.setPositiveButton("Search", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + EditText et = (EditText) rootView.findViewById(R.id.EditText); + dialog.dismiss(); + if (et.getText().toString().length() >= 2) { + startNameSearch(et.getText().toString()); + } else { + MessageBox.showMessage(StationList.this, "Two characters minimum" ); + } + } + }); + builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + return builder.create(); + default: return super.onCreateDialog(id); } @@ -134,7 +258,6 @@ } - @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); @@ -148,17 +271,108 @@ break; } } + + @Override + protected void onListItemClick(ListView l, View v, int position, long id) { + super.onListItemClick(l, v, position, id); + + StationBean station = stations.get(position); + + double latitude = station.getLatitude(); + double longitude = station.getLongitude(); + + + + Intent intent = new Intent(this, DepartureList.class); + intent.putExtra("name", station.getName()); + intent.putExtra("distance", station.getDistance()); + intent.putExtra("latitude", latitude); + intent.putExtra("longitude", longitude); + intent.putExtra("stationid", station.getId()); + intent.putExtra("address", station.getAddress()); + startActivity(intent); + } + + ///////////////////////////////////////////////////////////// + // public void startLookup() { isRunning = true; + dialogMessage = "Wait for location fix"; showDialog(DLG_PROGRESS); locator.locateStations(); stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000); } + + void startNameSearch(String name) { + dialogMessage = "Finding stations by name"; + showDialog(DLG_PROGRESS); + + findStationsTask = new FindStationsTask(); + findStationsTask.searchByName(name, locator.getLocation()); + findStationsTask.execute(); + + } + + public void startFavoriteLookup() { + + if (favorites.size() > 0) { + dialogMessage = "Loading favorites"; + showDialog(DLG_PROGRESS); + + findStationsTask = new FindStationsTask(); + findStationsTask.searchByIds(favorites.toString(), locator.getLocation()); + findStationsTask.execute(); + } else { + MessageBox.showMessage(this, "Favorite list is empty"); + } + } + + + + void startLocatorTask() + { + dialogMessage = "Finding nearby stations"; + showDialog(DLG_PROGRESS); + + findStationsTask = new FindStationsTask(); + findStationsTask.searchByLocation( locator.getLocation() ); + findStationsTask.execute(); + } + + String lookupAddress(double latitude, double longitude) { + + Geocoder coder = new Geocoder(this, new Locale("da")); + StringBuilder sb = new StringBuilder(); + Log.i("lookupaddr", "" + latitude + "/" + longitude); + try { + List
addressList = coder.getFromLocation(latitude, longitude, 1); + Address addr = addressList.get(0); + + + int max = addr.getMaxAddressLineIndex(); + for (int i=0; i0) + sb.append(", "); + + sb.append(addr.getAddressLine(i)); + } + + + } catch (Exception e) { + Log.e("DepartureList", "geocoder failed", e); + } + + return sb.toString(); + } + + + //////////////////////////////////////////////////////////////////////////// + // Inner classes - Handler stationsFetched = new Handler() { + class StationsFetchedHandler extends Handler { @Override public void handleMessage(Message msg) { @@ -167,6 +381,7 @@ dismissDialog(DLG_PROGRESS); startLocatorTask(); + location = GeoPair.fromLocation( locator.getLocation() ); break; @@ -183,7 +398,7 @@ dismissDialog(DLG_PROGRESS); AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this); - builder.setMessage("GPS fix timed out"); + builder.setMessage("Location fix timed out"); builder.setCancelable(true); builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { @@ -206,82 +421,68 @@ isRunning = false; } }; + - void startLocatorTask() - { - dialogMessage = "Finding nearby stations"; - showDialog(DLG_PROGRESS); + class FindStationsTask extends AsyncTask { - locatorTask = new LocatorTask(); - locatorTask.execute(); - } - - @Override - protected void onListItemClick(ListView l, View v, int position, long id) { - super.onListItemClick(l, v, position, id); - - StationBean station = stations.get(position); - - double latitude = station.getLatitude(); - double longitude = station.getLongitude(); - - + LookupMethod method = LookupMethod.MethodNone; + boolean success; + String name; + Location loc; + String ids; + + public void searchByName(String n, Location l) { + + method = LookupMethod.ByName; + loc = l; + name = n; + } - Intent intent = new Intent(this, DepartureList.class); - intent.putExtra("name", station.getName()); - intent.putExtra("distance", station.getDistance()); - intent.putExtra("latitude", latitude); - intent.putExtra("longitude", longitude); - intent.putExtra("stationid", station.getId()); - intent.putExtra("address", station.getAddress()); - startActivity(intent); - } - - String lookupAddress(double latitude, double longitude) { + public void searchByLocation(Location l) { + method = LookupMethod.ByLocation; + loc = l; + } - Geocoder coder = new Geocoder(this, new Locale("da")); - StringBuilder sb = new StringBuilder(); - Log.i("lookupaddr", "" + latitude + "/" + longitude); - try { - List
addressList = coder.getFromLocation(latitude, longitude, 1); - Address addr = addressList.get(0); - - - int max = addr.getMaxAddressLineIndex(); - for (int i=0; i0) - sb.append(", "); - - sb.append(addr.getAddressLine(i)); - } - + public void searchByIds(String id, Location l) { - } catch (Exception e) { - Log.e("DepartureList", "geocoder failed", e); + method = LookupMethod.ByList; + loc = l; + ids = id; } - return sb.toString(); - } - - class LocatorTask extends AsyncTask { - boolean success; @Override protected void onPreExecute() { + if (method.equals(LookupMethod.MethodNone)) + throw new RuntimeException("Method not set"); super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { - Location loc = locator.getLocation(); - success = stationProvider.lookupStations(loc); + + if (method.equals(LookupMethod.ByLocation)) + success = stationProvider.lookupStations(loc); + + if (method.equals(LookupMethod.ByName)) + success = stationProvider.lookupStationsByName(name); + if (method.equals(LookupMethod.ByList)) + success = stationProvider.lookupStationsByIds(ids); + Location dummy = new Location("gps"); List stations = stationProvider.getStations(); - for (StationBean station : stations) { + + for (StationBean station : stations) { String addr = lookupAddress(station.getLatitude(), station.getLongitude()); station.setAddress(addr); - } + + if (method.equals(LookupMethod.ByName) || method.equals(LookupMethod.ByList)) { + dummy.setLatitude(station.getLatitude()); + dummy.setLongitude(station.getLongitude()); + station.setDistance( (int)loc.distanceTo(dummy) ); + } + } return null; } @@ -322,4 +523,44 @@ } } } + + + class FavoritesMenu implements OnCreateContextMenuListener { + private final static int FAVORITES_ADD = 9001; + private final static int FAVORITES_REMOVE = 9002; + + private int selectedPosition; + + + @Override + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { + + AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; + selectedPosition = info.position; + int stationID = stations.get(selectedPosition).getId(); + + if (!favorites.contains(stationID)) { + menu.add(0, FAVORITES_ADD, 0, "Add to favorites"); + } else { + menu.add(0, FAVORITES_REMOVE, 0, "Remove from favorites"); + } + + } + + public void onContextItemSelected(MenuItem item) { + StationBean sb = stations.get(selectedPosition); + + int stationID = sb.getId(); + if (item.getItemId() == FAVORITES_ADD) { + favorites.add(stationID); + Toast.makeText(StationList.this, "Station added", Toast.LENGTH_SHORT).show(); + } else { + favorites.remove(stationID); + Toast.makeText(StationList.this, "Station removed", Toast.LENGTH_SHORT).show(); + } + Editor ed = prefs.edit(); + ed.putString("favorites", favorites.toString()); + ed.commit(); + } + } } \ No newline at end of file