--- android/TrainInfo/src/dk/thoerup/traininfo/StationList.java 2009/10/10 11:34:35 435 +++ android/TrainInfo/src/dk/thoerup/traininfo/StationList.java 2010/06/13 13:45:37 843 @@ -2,8 +2,9 @@ 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; @@ -12,13 +13,12 @@ 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; 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; @@ -38,32 +38,40 @@ import dk.thoerup.traininfo.util.IntSet; import dk.thoerup.traininfo.util.MessageBox; +import static dk.thoerup.traininfo.R.string.*; + 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_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 OPTIONS_GPSINFO = 2004; + public static final int DLG_PROGRESS = 3001; public static final int DLG_STATIONNAME = 3002; - /** Called when the activity is first created. */ + 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(); GeoPair location = new GeoPair(); - + + boolean isLaunchedforShortcut; boolean isRunning = false; List stations = new ArrayList(); @@ -73,14 +81,8 @@ FavoritesMenu contextMenu = new FavoritesMenu(); IntSet favorites = new IntSet(); - - static enum LookupMethod { - ByLocation, - ByName, - ByList, - MethodNone - } - + + WelcomeScreen.ListType listType; SharedPreferences prefs; /////////////////////////////////////////////////////////////////////////////////////////// @@ -90,7 +92,7 @@ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.main); + setContentView(R.layout.stationlist); adapter = new StationListAdapter(this); @@ -99,7 +101,7 @@ ListView lv = getListView(); lv.setOnCreateContextMenuListener(contextMenu); - locator = new LocationLookup(this, stationsFetched); + locationLookup = new LocationLookup(this, stationsFetched); prefs = getSharedPreferences("TrainStation", 0); @@ -108,14 +110,95 @@ favorites.fromString(favoriteString); } + listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type"); + setTitle(); + + isLaunchedforShortcut = getIntent().getBooleanExtra("shortcut", false); + if (savedInstanceState == null) { - startLookup(); + + + switch (listType) { + case ListNearest: + startLookup(); + break; + case ListSearch: + this.showDialogSafe(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(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); + } + + + /* these 3 dialogs helper functions are very rude and ugly hack + * to remove these auto-reported exceptions + * - android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@436aaef8 is not valid; is your activity running? + * - java.lang.IllegalArgumentException: View not attached to window manager + */ + + public void showDialogSafe(int id) { + try { + showDialog(id); + } catch (Exception e) { + Log.e("StationList", "showDialog failed", e); + } + } + + public void dismissDialogSafe(int id) { + try { + dismissDialog(id); + } catch (Exception e) { + Log.e("StationList", "dismissDialog failed", e); + } + } + public void dismissDialogSafe(Dialog dlg) { + try { + dlg.dismiss(); + } catch (Exception e) { + Log.e("StationList", "dismissDialog failed", e); + } + } + + public void builderShowSafe(AlertDialog.Builder builder) { + try { + builder.show(); + } catch (Exception e) { + Log.e("StationList", "builder.show() failed", e); + } + + } + /* EOF rude and ugly dialog hack */ + @Override @@ -125,6 +208,7 @@ dialog.dismiss(); outState.putSerializable("stations", (ArrayList) stations); outState.putSerializable("location", location); + } @@ -133,20 +217,12 @@ public boolean onCreateOptionsMenu(Menu menu) { MenuItem item; - item = menu.add(0, OPTIONS_RESCAN, 0, "Find 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, "Show station map"); + item = menu.add(0, OPTIONS_MAP, 0, getString(stationlist_stationmap)); 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); + item = menu.add(0, OPTIONS_GPSINFO, 0, getString(stationlist_gpsinfo)); + item.setIcon(android.R.drawable.ic_menu_mapmode); + return true; } @@ -154,21 +230,11 @@ public boolean onOptionsItemSelected(MenuItem item) { boolean retval = true; - + //TODO: Cleanup 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", location ); ArrayList stationPoints = new ArrayList(); for (StationBean st : stations ) { @@ -179,18 +245,19 @@ startActivity(intent); break; - case OPTIONS_ABOUT: - String ver = this.getResources().getString(R.string.app_version); - - Location loc = locator.getLocation(); + case OPTIONS_GPSINFO: + Location loc = locationLookup.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"); - + 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()); break; default: @@ -209,6 +276,19 @@ } + + 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(); + } @@ -218,7 +298,7 @@ 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: @@ -228,23 +308,25 @@ AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setTitle("Station search"); + builder.setTitle( getString(stationlist_stationsearch) ); builder.setView(rootView); builder.setCancelable(true); - builder.setPositiveButton("Search", new DialogInterface.OnClickListener() { + 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(); - if (et.getText().toString().length() >= 2) { - startNameSearch(et.getText().toString()); + String search = et.getText().toString().trim(); + if (search.length() >= 2) { + startNameSearch(search); } else { - MessageBox.showMessage(StationList.this, "Two characters minimum" ); + showMessageAndClose( getString(stationlist_twocharmin) ); } } }); - builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + 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(); @@ -275,55 +357,52 @@ 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); + 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; - dialogMessage = "Wait for location fix"; - showDialog(DLG_PROGRESS); + isRunning = true; + dialogMessage = getString( stationlist_waitforlocation ); + showDialogSafe(DLG_PROGRESS); - locator.locateStations(); + locationLookup.locateStations(); stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000); } void startNameSearch(String name) { - dialogMessage = "Finding stations by name"; - showDialog(DLG_PROGRESS); + dialogMessage = getString( stationlist_findbyname ); + showDialogSafe(DLG_PROGRESS); - locatorTask = new LocatorTask(); - locatorTask.searchByName(name, locator.getLocation()); - locatorTask.execute(); + findStationsTask = new FindStationsTask(); + findStationsTask.searchByName(name); + findStationsTask.execute(); } public void startFavoriteLookup() { - if (favorites.toString().length() > 0) { - dialogMessage = "Loading favorites"; - showDialog(DLG_PROGRESS); - - locatorTask = new LocatorTask(); - locatorTask.searchByIds(favorites.toString(), locator.getLocation()); - locatorTask.execute(); + if (favorites.size() > 0) { + dialogMessage = getString( stationlist_loadfavorites ); + showDialogSafe(DLG_PROGRESS); + + findStationsTask = new FindStationsTask(); + findStationsTask.searchByIds( favorites.toString() ); + findStationsTask.execute(); } else { - MessageBox.showMessage(this, "Favorite list is empty"); + showMessageAndClose( getString( stationlist_nofavorites ) ); } } @@ -331,41 +410,14 @@ void startLocatorTask() { - dialogMessage = "Finding nearby stations"; - showDialog(DLG_PROGRESS); + dialogMessage = getString( stationlist_findingnearby ); + showDialogSafe(DLG_PROGRESS); - locatorTask = new LocatorTask(); - locatorTask.searchByLocation( locator.getLocation() ); - locatorTask.execute(); + findStationsTask = new FindStationsTask(); + findStationsTask.searchByLocation( locationLookup.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 @@ -376,41 +428,41 @@ switch (msg.what) { case GOTLOCATION: - dismissDialog(DLG_PROGRESS); + dismissDialogSafe(DLG_PROGRESS); startLocatorTask(); - location = GeoPair.fromLocation( locator.getLocation() ); + location = GeoPair.fromLocation( locationLookup.getLocation() ); break; case NOPROVIDER: - dismissDialog(DLG_PROGRESS); - MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps."); + dismissDialogSafe(DLG_PROGRESS); + MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider) ); break; case LOCATIONFIXTIMEOUT: if (isRunning) { - locator.stopSearch(); - if (locator.hasLocation()) { + locationLookup.stopSearch(); + if (locationLookup.hasLocation()) { stationsFetched.sendEmptyMessage( GOTLOCATION ); } else { - dismissDialog(DLG_PROGRESS); + dismissDialogSafe(DLG_PROGRESS); AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this); - builder.setMessage("Location fix timed out"); + builder.setMessage( getString( stationlist_gpstimeout) ); 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(); startLookup(); } }); - builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + builder.setNegativeButton( getString(generic_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } - }); - builder.show(); + }); + builderShowSafe(builder); // builder.show() } } @@ -421,7 +473,7 @@ }; - class LocatorTask extends AsyncTask { + class FindStationsTask extends AsyncTask { LookupMethod method = LookupMethod.MethodNone; boolean success; @@ -429,10 +481,9 @@ Location loc; String ids; - public void searchByName(String n, Location l) { + public void searchByName(String n) { method = LookupMethod.ByName; - loc = l; name = n; } @@ -441,10 +492,9 @@ loc = l; } - public void searchByIds(String id, Location l) { + public void searchByIds(String id) { method = LookupMethod.ByList; - loc = l; ids = id; } @@ -458,29 +508,21 @@ @Override protected Void doInBackground(Void... params) { - - if (method.equals(LookupMethod.ByLocation)) + + switch (method) { + case ByLocation: success = stationProvider.lookupStations(loc); - - if (method.equals(LookupMethod.ByName)) + break; + case ByName: success = stationProvider.lookupStationsByName(name); - - if (method.equals(LookupMethod.ByList)) + 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) { - 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; } @@ -488,36 +530,63 @@ @Override protected void onPostExecute(Void result) { super.onPostExecute(result); - dialog.dismiss(); + dismissDialogSafe(dialog); + if (success) { - if (stationProvider.getStations().size() == 0) - MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?! + if (stationProvider.getStations().size() == 0) { + showMessageAndClose(getString(stationlist_nostations)); + } stations = stationProvider.getStations(); 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_nearbyerror)); 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() { + startNameSearch( 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(); + }); + + builderShowSafe(builder); // builder.show() } } } @@ -537,10 +606,10 @@ selectedPosition = info.position; int stationID = stations.get(selectedPosition).getId(); - if (!favorites.hasInt(stationID)) { - menu.add(0, FAVORITES_ADD, 0, "Add to favorites"); + if (!favorites.contains(stationID)) { + menu.add(0, FAVORITES_ADD, 0, getString(stationlist_addfavorite) ); } else { - menu.add(0, FAVORITES_REMOVE, 0, "Remove from favorites"); + menu.add(0, FAVORITES_REMOVE, 0, getString(stationlist_removefavorite) ); } } @@ -551,10 +620,17 @@ int stationID = sb.getId(); if (item.getItemId() == FAVORITES_ADD) { favorites.add(stationID); - Toast.makeText(StationList.this, "Station added", Toast.LENGTH_SHORT).show(); + Toast.makeText(StationList.this, getString(stationlist_stationadded), Toast.LENGTH_SHORT).show(); } else { + favorites.remove(stationID); - Toast.makeText(StationList.this, "Station removed", Toast.LENGTH_SHORT).show(); + Toast.makeText(StationList.this, getString(stationlist_stationremoved), Toast.LENGTH_SHORT).show(); + + + if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) { + stations.remove(selectedPosition); + adapter.notifyDataSetChanged(); + } } Editor ed = prefs.edit(); ed.putString("favorites", favorites.toString());