--- android/TrainInfo/src/dk/thoerup/traininfo/StationList.java 2009/09/30 16:40:48 369 +++ android/TrainInfo/src/dk/thoerup/traininfo/StationList.java 2011/03/30 17:26:50 1245 @@ -1,116 +1,274 @@ package dk.thoerup.traininfo; +import static dk.thoerup.traininfo.R.string.app_name; +import static dk.thoerup.traininfo.R.string.generic_cancel; +import static dk.thoerup.traininfo.R.string.generic_retry; +import static dk.thoerup.traininfo.R.string.generic_search; +import static dk.thoerup.traininfo.R.string.stationlist_accuracy; +import static dk.thoerup.traininfo.R.string.stationlist_addfavorite; +import static dk.thoerup.traininfo.R.string.stationlist_favorites; +import static dk.thoerup.traininfo.R.string.stationlist_fetcherror; +import static dk.thoerup.traininfo.R.string.stationlist_findbyname; +import static dk.thoerup.traininfo.R.string.stationlist_findingnearby; +import static dk.thoerup.traininfo.R.string.stationlist_gpsinfo; +import static dk.thoerup.traininfo.R.string.stationlist_gpstimeout; +import static dk.thoerup.traininfo.R.string.stationlist_latitude; +import static dk.thoerup.traininfo.R.string.stationlist_loadfavorites; +import static dk.thoerup.traininfo.R.string.stationlist_locationinfo; +import static dk.thoerup.traininfo.R.string.stationlist_longitude; +import static dk.thoerup.traininfo.R.string.stationlist_nearbystations; +import static dk.thoerup.traininfo.R.string.stationlist_nofavorites; +import static dk.thoerup.traininfo.R.string.stationlist_nolocation; +import static dk.thoerup.traininfo.R.string.stationlist_nolocationprovider; +import static dk.thoerup.traininfo.R.string.stationlist_nostations; +import static dk.thoerup.traininfo.R.string.stationlist_obtainedby; +import static dk.thoerup.traininfo.R.string.stationlist_removefavorite; +import static dk.thoerup.traininfo.R.string.stationlist_satellitecount; +import static dk.thoerup.traininfo.R.string.stationlist_search; +import static dk.thoerup.traininfo.R.string.stationlist_stationadded; +import static dk.thoerup.traininfo.R.string.stationlist_stationmap; +import static dk.thoerup.traininfo.R.string.stationlist_stationremoved; +import static dk.thoerup.traininfo.R.string.stationlist_stationsearch; +import static dk.thoerup.traininfo.R.string.stationlist_twocharmin; +import static dk.thoerup.traininfo.R.string.stationlist_waitforlocation; + import java.util.ArrayList; -import java.util.List; -import java.util.Locale; +import android.app.Activity; 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.location.Address; -import android.location.Geocoder; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; 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.android.traininfo.common.StationBean; +import dk.thoerup.android.traininfo.common.StationBean.StationEntry; 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 { - 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 = 2001; - public static final int OPTIONS_ABOUT = 2002; - public static final int DLG_PROGRESS = 1001; - /** Called when the activity is first created. */ + 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; + + + public static final int GPS_TIMEOUT_MS = 15000; //how long are we willing to wait for gps fix -in milliseconds + + + static enum LookupMethod { + ByLocation, + ByName, + ByList, + MethodNone + } + + String dialogMessage = ""; ProgressDialog dialog; - LocationLookup locator = null; - LocatorTask locatorTask; + LocationLookup locationLookup = null; + FindStationsTask findStationsTask; + StationsFetchedHandler stationsFetched = new StationsFetchedHandler(); - boolean isRunning = false; - List stations = new ArrayList(); + //GeoPair location = new GeoPair(); + + boolean isLaunchedforShortcut; + + StationBean stations = new StationBean(); 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); adapter = new StationListAdapter(this); setListAdapter(adapter); - locator = new LocationLookup(this, stationsFetched); + ListView lv = getListView(); + lv.setOnCreateContextMenuListener(contextMenu); + + locationLookup = new LocationLookup(this); + + + prefs = getSharedPreferences("TrainStation", 0); + String favoriteString = prefs.getString("favorites", ""); + if (! favoriteString.equals("") ) { + favorites.fromString(favoriteString); + } + + listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type"); + setTitle(); + + isLaunchedforShortcut = getIntent().getBooleanExtra("shortcut", false); + + ProviderFactory.purgeOldEntries(); //cleanup before fetching more data + if (savedInstanceState == null) { - startLookup(); + + + switch (listType) { + case ListNearest: + startNearestLookup(); + break; + case ListSearch: + showDialog(DLG_STATIONNAME); + break; + case ListFavorites: + startFavoriteLookup(); + break; + default: + // Not possible !?! + } + } else { - stations = (ArrayList) savedInstanceState.getSerializable("stations"); + stations = (StationBean) savedInstanceState.getSerializable("stations"); adapter.setStations(stations); } + + } + + + + + + + @Override + protected void onDestroy() { + super.onDestroy(); + + stationsFetched.removeMessages(0); + + + if (locationLookup != null) { + locationLookup.stopSearch(); + } + if (findStationsTask != null) { + findStationsTask.cancel(true); + } + } + + + protected void setTitle() { + String dialogTitle = getResources().getString(app_name); + switch (listType) { + case ListNearest: + dialogTitle += " - " + getString(stationlist_nearbystations); + break; + case ListSearch: + dialogTitle += " - " + getString(stationlist_search); + break; + case ListFavorites: + dialogTitle += " - " + getString(stationlist_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("stations", (StationBean) stations); + } @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_MAP, 0, getString(stationlist_stationmap)); + item.setIcon(android.R.drawable.ic_menu_mapmode); + + item = menu.add(0, OPTIONS_GPSINFO, 0, getString(stationlist_gpsinfo)); + item.setIcon(android.R.drawable.ic_menu_mapmode); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { - boolean retval; - + boolean retval = true; + + //TODO: Cleanup switch (item.getItemId()) { case OPTIONS_MAP: Intent intent = new Intent(this,StationMapView.class); - intent.putExtra("userlocation", GeoPair.fromLocation(locator.getLocation()) ); ArrayList stationPoints = new ArrayList(); - for (StationBean st : stations ) { + for (StationEntry st : stations.entries ) { stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) ); } intent.putExtra("stations", stationPoints); startActivity(intent); - retval = true; + break; + case OPTIONS_GPSINFO: + Location loc = locationLookup.getLocation(); + StringBuffer message = new StringBuffer(); + message.append( getString(stationlist_locationinfo) ).append(":\n"); + if (loc != null) { + message.append( getString(stationlist_obtainedby) ).append( loc.getProvider() ).append("\n"); + message.append( getString(stationlist_accuracy) ).append( (int)loc.getAccuracy()).append("m\n"); + message.append( getString(stationlist_latitude) ).append( (float)loc.getLatitude()).append("\n"); + message.append( getString(stationlist_longitude) ).append( (float)loc.getLongitude() ).append("\n"); + } else { + message.append( getString(stationlist_nolocation) ); + } + + MessageBox.showMessage(this, message.toString(), false); break; default: retval = super.onOptionsItemSelected(item); @@ -118,15 +276,71 @@ return retval; } + + + + @Override + public boolean onContextItemSelected(MenuItem item) { + contextMenu.onContextItemSelected(item); + return true; + + + } + + public void showMessageAndClose(String message) { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setMessage(message) + .setCancelable(false) + .setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + StationList.this.finish(); + } + }) + .show(); + } + + + @Override protected Dialog onCreateDialog(int id) { switch (id) { case DLG_PROGRESS: ProgressDialog dlg = new ProgressDialog(this); - dlg.setMessage("Wait for location fix"); + dlg.setMessage( getString(stationlist_waitforlocation) ); 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( getString(stationlist_stationsearch) ); + builder.setView(rootView); + builder.setCancelable(true); + builder.setPositiveButton( getString(generic_search), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + EditText et = (EditText) rootView.findViewById(R.id.EditText); + dialog.dismiss(); + String search = et.getText().toString().trim(); + if (search.length() >= 2) { + startNameLookup(search); + } else { + showMessageAndClose( getString(stationlist_twocharmin) ); + } + } + }); + builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + StationList.this.finish(); // Close this Activity + } + }); + return builder.create(); + default: return super.onCreateDialog(id); } @@ -134,7 +348,6 @@ } - @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); @@ -148,141 +361,198 @@ break; } } + + @Override + protected void onListItemClick(ListView l, View v, int position, long id) { + super.onListItemClick(l, v, position, id); + + StationEntry station = stations.entries.get(position); + + if (isLaunchedforShortcut == true) { + Intent i = new Intent(); + i.putExtra("station", station); + setResult(Activity.RESULT_OK, i); + finish(); + } else { + Intent intent = new Intent(this, DepartureList.class); + intent.putExtra("stationbean", station); + startActivity(intent); + } + } + + ///////////////////////////////////////////////////////////// + // - public void startLookup() { - isRunning = true; + public void startNearestLookup() { + dialogMessage = getString( stationlist_waitforlocation ); showDialog(DLG_PROGRESS); - locator.locateStations(); - stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000); + locationLookup.locateStations(); + stationsFetched.sendEmptyMessageDelayed(0, 500); + } + + void startNameLookup(String name) { + dialogMessage = getString( stationlist_findbyname ); + showDialog(DLG_PROGRESS); + + findStationsTask = new FindStationsTask(); + findStationsTask.searchByName(name); + findStationsTask.execute(); + + } + + public void startFavoriteLookup() { + + if (favorites.size() > 0) { + dialogMessage = getString( stationlist_loadfavorites ); + showDialog(DLG_PROGRESS); + + findStationsTask = new FindStationsTask(); + findStationsTask.searchByIds( favorites.toString() ); + findStationsTask.execute(); + } else { + showMessageAndClose( getString( stationlist_nofavorites ) ); + } } - Handler stationsFetched = new Handler() { + + void startLocatorTask() + { + dialogMessage = getString( stationlist_findingnearby ); + showDialog(DLG_PROGRESS); + + findStationsTask = new FindStationsTask(); + findStationsTask.searchByLocation( locationLookup.getLocation() ); + findStationsTask.execute(); + } + + + //////////////////////////////////////////////////////////////////////////// + // Inner classes + + class StationsFetchedHandler extends Handler { @Override public void handleMessage(Message msg) { - switch (msg.what) { + LocationLookup.LookupStates state = locationLookup.getState(); + + + switch (state) { case GOTLOCATION: dismissDialog(DLG_PROGRESS); - + startLocatorTask(); - - break; + + return; case NOPROVIDER: dismissDialog(DLG_PROGRESS); - MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps."); - break; - case LOCATIONFIXTIMEOUT: - if (isRunning) { - locator.stopSearch(); - if (locator.hasLocation()) { - stationsFetched.sendEmptyMessage( GOTLOCATION ); - } else { - dismissDialog(DLG_PROGRESS); - - AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this); - builder.setMessage("GPS 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(); + MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider), true ); + //StationList.this.finish(); + return; + case IDLE: + Log.e("TrainInfo", "How did this happen ???"); + dismissDialog(DLG_PROGRESS); // how did we get here ?? + return; + + } + + + + if (locationLookup.elapsedTime() >= GPS_TIMEOUT_MS) { + dismissDialog(DLG_PROGRESS); + + + locationLookup.stopSearch(); + + if (locationLookup.hasLocation()) { + startLocatorTask(); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this); + builder.setMessage( getString( stationlist_gpstimeout) ); + builder.setCancelable(true); + builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + startNearestLookup(); + + } + }); + builder.setNegativeButton( getString(generic_cancel), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + StationList.this.finish(); // Close this Activity + } + }); + builder.show(); - } } - break; + } else { + if (locationLookup.hasGps()) { + int count = locationLookup.getSatCount(); + String dialogMessage = getString( stationlist_waitforlocation ) + "\n" + getString( stationlist_satellitecount ) + ": " + count; + dialog.setMessage( dialogMessage ); + } + this.sendEmptyMessageDelayed(0, 500); } - isRunning = false; + } - }; - - void startLocatorTask() - { - dialogMessage = "Finding nearby stations"; - showDialog(DLG_PROGRESS); - - 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(); + + class FindStationsTask extends AsyncTask { - 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) { + LookupMethod method = LookupMethod.MethodNone; + String name; + Location loc; + String ids; - 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 searchByName(String n) { + method = LookupMethod.ByName; + name = n; + } + + public void searchByLocation(Location l) { + method = LookupMethod.ByLocation; + loc = l; + } + + public void searchByIds(String id) { - } catch (Exception e) { - Log.e("DepartureList", "geocoder failed", e); + method = LookupMethod.ByList; + 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); - - - List stations = stationProvider.getStations(); - for (StationBean station : stations) { - String addr = lookupAddress(station.getLatitude(), station.getLongitude()); - station.setAddress(addr); + + switch (method) { + case ByLocation: + stations = stationProvider.lookupStationsByLocation(loc); + break; + case ByName: + stations = stationProvider.lookupStationsByName(name); + break; + case ByList: + stations = stationProvider.lookupStationsByIds(ids); + break; + default: + stations = null; // not possible } + return null; } @@ -291,35 +561,111 @@ super.onPostExecute(result); dialog.dismiss(); - if (success) { - if (stationProvider.getStations().size() == 0) - MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?! - stations = stationProvider.getStations(); + + if (stations != null) { + if (stations.entries.size() == 0) { + showMessageAndClose(getString(stationlist_nostations)); + } + + StationList.this.getListView().invalidateViews(); adapter.setStations( stations ); + } else { //communication or parse errors AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this); - builder.setMessage("Error on finding nearby stations"); + builder.setMessage(getString(stationlist_fetcherror)); builder.setCancelable(true); - builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() { + builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); - stationsFetched.post( new Runnable() { - @Override - public void run() { - startLocatorTask(); - } - }); + Runnable runner = null; + switch (method) { + case ByLocation: + runner = new Runnable() { + @Override + public void run() { + startLocatorTask(); + } + }; + break; + case ByName: + runner = new Runnable() { + @Override + public void run() { + startNameLookup( FindStationsTask.this.name ); + } + }; + break; + case ByList: + runner = new Runnable() { + @Override + public void run() { + startFavoriteLookup(); + } + }; + break; + } + + stationsFetched.post( runner ); } }); - builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); + StationList.this.finish(); } - }); - builder.show(); + }); + + 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.entries.get(selectedPosition).getId(); + + if (!favorites.contains(stationID)) { + menu.add(0, FAVORITES_ADD, 0, getString(stationlist_addfavorite) ); + } else { + menu.add(0, FAVORITES_REMOVE, 0, getString(stationlist_removefavorite) ); + } + + } + + public void onContextItemSelected(MenuItem item) { + StationEntry sb = stations.entries.get(selectedPosition); + + int stationID = sb.getId(); + if (item.getItemId() == FAVORITES_ADD) { + favorites.add(stationID); + Toast.makeText(StationList.this, getString(stationlist_stationadded), Toast.LENGTH_SHORT).show(); + } else { + + favorites.remove(stationID); + Toast.makeText(StationList.this, getString(stationlist_stationremoved), Toast.LENGTH_SHORT).show(); + + + if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) { + stations.entries.remove(selectedPosition); + adapter.notifyDataSetChanged(); + } } + Editor ed = prefs.edit(); + ed.putString("favorites", favorites.toString()); + ed.commit(); } } } \ No newline at end of file