--- android/TrainInfo/src/dk/thoerup/traininfo/TrainInfoList.java 2009/09/11 12:24:53 319 +++ android/TrainInfo/src/dk/thoerup/traininfo/StationList.java 2009/10/29 11:38:58 484 @@ -4,10 +4,14 @@ import java.util.List; import java.util.Locale; +import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; 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; @@ -16,72 +20,252 @@ 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 TrainInfoList extends ListActivity { - public static final int GOTLOCATION = 1; - public static final int GOTSTATIONLIST = 2; - public static final int NOPROVIDER = 3; - public static final int FIXTIMEOUT = 4; - public static final int LOOKUPSTATIONFAILED = 5; +public class StationList extends ListActivity { + public static final int GOTLOCATION = 1001; + public static final int GOTSTATIONLIST = 1002; + public static final int NOPROVIDER = 1003; + public static final int LOCATIONFIXTIMEOUT = 1004; + + public static final int OPTIONS_MAP = 2003; + public static final int OPTIONS_GPSINFO = 2004; + + + + + public static final int DLG_PROGRESS = 3001; + public static final int DLG_STATIONNAME = 3002; + + static enum LookupMethod { + ByLocation, + ByName, + ByList, + MethodNone + } - public static final int DLG_PROGRESS = 1; - /** Called when the activity is first created. */ + String dialogMessage = ""; ProgressDialog dialog; - LocationLookup locator = null; - LocatorTask locatorTask = new LocatorTask(); + LocationLookup locationLookup = null; + 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(); + + WelcomeScreen.ListType listType; + SharedPreferences prefs; + + /////////////////////////////////////////////////////////////////////////////////////////// + //Activity call backs - StationListAdapter adapter = null; @SuppressWarnings("unchecked") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.main); + setContentView(R.layout.stationlist); - LocationLookup.removeMockLocation(this); - //StationLocator.injectMockLocation(this); adapter = new StationListAdapter(this); setListAdapter(adapter); - locator = new LocationLookup(this, stationsFetched); + ListView lv = getListView(); + lv.setOnCreateContextMenuListener(contextMenu); + + locationLookup = new LocationLookup(this, stationsFetched); + + + prefs = getSharedPreferences("TrainStation", 0); + String favoriteString = prefs.getString("favorites", ""); + if (! favoriteString.equals("") ) { + favorites.fromString(favoriteString); + } + + listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type"); + setTitle(); + if (savedInstanceState == null) { - startLookup(); + + + switch (listType) { + case ListNearest: + startLookup(); + break; + case ListSearch: + this.showDialog(DLG_STATIONNAME); + break; + case ListFavorites: + startFavoriteLookup(); + break; + default: + // Not possible !?! + } + } else { stations = (ArrayList) savedInstanceState.getSerializable("stations"); adapter.setStations(stations); + location = (GeoPair) savedInstanceState.getSerializable("location"); } + } + protected void setTitle() { + String dialogTitle = getResources().getString(R.string.app_name); + switch (listType) { + case ListNearest: + dialogTitle += " - Nearby stations"; + break; + case ListSearch: + dialogTitle += " - Search"; + break; + case ListFavorites: + dialogTitle += " - Favorites"; + break; + default: + dialogTitle = "";//not possible + } + setTitle(dialogTitle); + } + + + + @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) { + MenuItem item; + + item = menu.add(0, OPTIONS_MAP, 0, "Station map"); + item.setIcon(android.R.drawable.ic_menu_mapmode); + + item = menu.add(0, OPTIONS_GPSINFO, 0, "GPS Info"); + item.setIcon(android.R.drawable.ic_menu_mapmode); + + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + boolean retval = true; + + //TODO: Cleanup + switch (item.getItemId()) { + case OPTIONS_MAP: + + Intent intent = new Intent(this,StationMapView.class); + intent.putExtra("userlocation", location ); + + ArrayList stationPoints = new ArrayList(); + for (StationBean st : stations ) { + stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) ); + } + + intent.putExtra("stations", stationPoints); + + startActivity(intent); + break; + case OPTIONS_GPSINFO: + Location loc = locationLookup.getLocation(); + StringBuffer message = new StringBuffer(); + 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); + } + + return retval; + } + + + + @Override + public boolean onContextItemSelected(MenuItem item) { + contextMenu.onContextItemSelected(item); + return true; + + + } + + + + + @Override protected Dialog onCreateDialog(int id) { switch (id) { case DLG_PROGRESS: ProgressDialog dlg = new ProgressDialog(this); dlg.setMessage("Wait for location fix"); dlg.setCancelable(false); - return dlg; + 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); } @@ -89,61 +273,19 @@ } - @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); switch (id) { case DLG_PROGRESS: this.dialog = (ProgressDialog) dialog; + if (!dialogMessage.equals("")) { + this.dialog.setMessage(dialogMessage); + dialogMessage = ""; + } break; } } - - public void startLookup() { - isRunning = true; - showDialog(DLG_PROGRESS); - - locator.locateStations(); - stationsFetched.sendEmptyMessageDelayed(FIXTIMEOUT, 20000); - } - - - Handler stationsFetched = new Handler() { - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case GOTLOCATION: - dialog.setMessage("Finding nearby stations"); - locatorTask.execute(); - break; - - case NOPROVIDER: - dialog.dismiss(); - MessageBox.showMessage(TrainInfoList.this,"No location provider enabled. Plase enable gps."); - break; - case FIXTIMEOUT: - dialog.dismiss(); - if (isRunning) { - locator.abortLocationListener(); - if (locator.hasLocation()) { - msg.what = GOTLOCATION; - handleMessage( msg ); // ToDo: ugly recursive call !!! - } else { - MessageBox.showMessage(TrainInfoList.this,"GPS fix timed out"); - } - } - break; - case LOOKUPSTATIONFAILED: - dialog.dismiss(); - MessageBox.showMessage(TrainInfoList.this,"Error on finding nearby stations"); - break; - } - isRunning = false; - } - }; - - @Override protected void onListItemClick(ListView l, View v, int position, long id) { @@ -166,6 +308,55 @@ startActivity(intent); } + ///////////////////////////////////////////////////////////// + // + + public void startLookup() { + isRunning = true; + dialogMessage = "Wait for location fix"; + showDialog(DLG_PROGRESS); + + locationLookup.locateStations(); + stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000); + } + + void startNameSearch(String name) { + dialogMessage = "Finding stations by name"; + showDialog(DLG_PROGRESS); + + findStationsTask = new FindStationsTask(); + findStationsTask.searchByName(name, locationLookup.getLocation()); + findStationsTask.execute(); + + } + + public void startFavoriteLookup() { + + if (favorites.size() > 0) { + dialogMessage = "Loading favorites"; + showDialog(DLG_PROGRESS); + + findStationsTask = new FindStationsTask(); + findStationsTask.searchByIds(favorites.toString(), locationLookup.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( locationLookup.getLocation() ); + findStationsTask.execute(); + } + + String lookupAddress(double latitude, double longitude) { Geocoder coder = new Geocoder(this, new Locale("da")); @@ -192,25 +383,133 @@ return sb.toString(); } - class LocatorTask extends AsyncTask { + + //////////////////////////////////////////////////////////////////////////// + // Inner classes + + class StationsFetchedHandler extends Handler { + @Override + public void handleMessage(Message msg) { + + switch (msg.what) { + case GOTLOCATION: + dismissDialog(DLG_PROGRESS); + + startLocatorTask(); + location = GeoPair.fromLocation( locationLookup.getLocation() ); + + break; + + case NOPROVIDER: + dismissDialog(DLG_PROGRESS); + MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps."); + break; + case LOCATIONFIXTIMEOUT: + if (isRunning) { + locationLookup.stopSearch(); + if (locationLookup.hasLocation()) { + stationsFetched.sendEmptyMessage( GOTLOCATION ); + } else { + dismissDialog(DLG_PROGRESS); + + AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this); + builder.setMessage("Location fix timed out"); + builder.setCancelable(true); + builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + startLookup(); + + } + }); + builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); + builder.show(); + + } + } + break; + } + isRunning = false; + } + }; + + + class FindStationsTask extends AsyncTask { + + 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; + } + + public void searchByLocation(Location l) { + method = LookupMethod.ByLocation; + loc = l; + } + + public void searchByIds(String id, Location l) { + + method = LookupMethod.ByList; + loc = l; + ids = id; + } + @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); + + switch (method) { + case ByLocation: + success = stationProvider.lookupStations(loc); + break; + case ByName: + success = stationProvider.lookupStationsByName(name); + break; + case ByList: + success = stationProvider.lookupStationsByIds(ids); + break; + default: + success = false; // not possible + } + 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)) { + if (loc != null) { //only do the distance calc if we have a location + dummy.setLatitude(station.getLatitude()); + dummy.setLongitude(station.getLongitude()); + station.setDistance( (int)loc.distanceTo(dummy) ); + } else { + station.setDistance(0); + } + } + + } return null; } @@ -220,15 +519,83 @@ super.onPostExecute(result); dialog.dismiss(); + if (success) { if (stationProvider.getStations().size() == 0) - MessageBox.showMessage(TrainInfoList.this, "No stations found!"); // this should not be possible !?! + MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?! stations = stationProvider.getStations(); adapter.setStations( stations ); } else { //communication or parse errors - MessageBox.showMessage(TrainInfoList.this, "Error finding stations!"); + AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this); + builder.setMessage("Error on finding nearby stations"); + builder.setCancelable(true); + builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + + stationsFetched.post( new Runnable() { + @Override + public void run() { + startLocatorTask(); + } + }); + } + }); + builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); + builder.show(); + } + } + } + + + 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(); + + + if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) { + stations.remove(selectedPosition); + adapter.notifyDataSetChanged(); + } } + Editor ed = prefs.edit(); + ed.putString("favorites", favorites.toString()); + ed.commit(); } } } \ No newline at end of file