--- android/TrainInfo/src/dk/thoerup/traininfo/StationList.java 2010/02/02 08:44:35 578 +++ android/TrainInfo/src/dk/thoerup/traininfo/StationList.java 2011/07/07 19:07:55 1547 @@ -1,9 +1,31 @@ package dk.thoerup.traininfo; -import java.util.ArrayList; -import java.util.List; +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.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_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_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_nolocationprovider; +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_waitforlocation; +import java.util.ArrayList; +import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; @@ -13,22 +35,24 @@ 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.text.Editable; +import android.text.TextWatcher; +import android.util.Log; import android.view.ContextMenu; -import android.view.LayoutInflater; +import android.view.ContextMenu.ContextMenuInfo; 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.TextView; import android.widget.Toast; +import dk.thoerup.android.traininfo.common.StationBean; +import dk.thoerup.android.traininfo.common.StationEntry; import dk.thoerup.traininfo.provider.ProviderFactory; import dk.thoerup.traininfo.provider.StationProvider; import dk.thoerup.traininfo.stationmap.GeoPair; @@ -36,22 +60,18 @@ 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_MAP = 2003; - public static final int OPTIONS_GPSINFO = 2004; - + + public static final int OPTIONS_MAP = 103; + public static final int OPTIONS_GPSINFO = 104; 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, @@ -64,13 +84,13 @@ String dialogMessage = ""; ProgressDialog dialog; LocationLookup locationLookup = null; - FindStationsTask findStationsTask; StationsFetchedHandler stationsFetched = new StationsFetchedHandler(); - GeoPair location = new GeoPair(); - - boolean isRunning = false; - List stations = new ArrayList(); + //GeoPair location = new GeoPair(); + + boolean isLaunchedforShortcut; + + StationBean stations = new StationBean(); StationProvider stationProvider = ProviderFactory.getStationProvider(); @@ -81,11 +101,11 @@ WelcomeScreen.ListType listType; SharedPreferences prefs; - + /////////////////////////////////////////////////////////////////////////////////////////// //Activity call backs - @SuppressWarnings("unchecked") + @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -98,7 +118,7 @@ ListView lv = getListView(); lv.setOnCreateContextMenuListener(contextMenu); - locationLookup = new LocationLookup(this, stationsFetched); + locationLookup = new LocationLookup(this); prefs = getSharedPreferences("TrainStation", 0); @@ -110,15 +130,19 @@ listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type"); setTitle(); + isLaunchedforShortcut = getIntent().getBooleanExtra("shortcut", false); + + ProviderFactory.purgeOldEntries(); //cleanup before fetching more data + if (savedInstanceState == null) { switch (listType) { case ListNearest: - startLookup(); + startNearestLookup(); break; - case ListSearch: - this.showDialog(DLG_STATIONNAME); + case ListSearch: + enableNamesearchField(); break; case ListFavorites: startFavoriteLookup(); @@ -128,12 +152,31 @@ } } else { - stations = (ArrayList) savedInstanceState.getSerializable("stations"); + stations = (StationBean) savedInstanceState.getSerializable("stations"); adapter.setStations(stations); - location = (GeoPair) savedInstanceState.getSerializable("location"); } } + + + + + + + @Override + protected void onDestroy() { + super.onDestroy(); + + stationsFetched.removeMessages(0); + + + if (locationLookup != null) { + locationLookup.stopSearch(); + } + + } + + protected void setTitle() { String dialogTitle = getResources().getString(app_name); switch (listType) { @@ -151,18 +194,46 @@ } setTitle(dialogTitle); + } + public void enableNamesearchField() { + final TextView stationSearch = (TextView) findViewById(R.id.stationsearch); + stationSearch.setVisibility( View.VISIBLE ); + stationSearch.addTextChangedListener( new TextWatcher() { + + @Override + public void afterTextChanged(Editable s) { + if (s.length() > 0) { + startNameLookup( s.toString() ); + } else { + stations = new StationBean(); + getListView().invalidateViews(); + adapter.setStations( stations ); + } + } + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + + }); + + + } + @Override public void onSaveInstanceState(Bundle outState) { if (dialog != null && dialog.isShowing()) dialog.dismiss(); - outState.putSerializable("stations", (ArrayList) stations); - outState.putSerializable("location", location); + outState.putSerializable("stations", (StationBean) stations); } @@ -176,23 +247,33 @@ 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); + item.setIcon(android.R.drawable.ic_menu_info_details); + boolean hasLoc = (locationLookup.getLocation() != null); + item.setEnabled(hasLoc); return true; } + + + @Override public boolean onOptionsItemSelected(MenuItem item) { boolean retval = true; - //TODO: Cleanup + switch (item.getItemId()) { case OPTIONS_MAP: + if ( stations == null || stations.entries == null || stations.entries.size() == 0 ) { + Toast.makeText(this, "No stations to show on map", Toast.LENGTH_SHORT).show(); //TODO: Translate + return true; + } + Intent intent = new Intent(this,StationMapView.class); ArrayList stationPoints = new ArrayList(); - for (StationBean st : stations ) { + for (StationEntry st : stations.entries ) { stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) ); } @@ -204,16 +285,14 @@ 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) ); - } + + 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"); + - MessageBox.showMessage(this, message.toString()); + MessageBox.showMessage(this, message.toString(), false); break; default: retval = super.onOptionsItemSelected(item); @@ -256,34 +335,6 @@ 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(); - if (et.getText().toString().length() >= 2) { - startNameSearch(et.getText().toString()); - } 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); @@ -310,44 +361,47 @@ protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); - StationBean station = stations.get(position); + StationEntry station = stations.entries.get(position); - Intent intent = new Intent(this, DepartureList.class); - intent.putExtra("stationbean", station); - 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; + public void startNearestLookup() { dialogMessage = getString( stationlist_waitforlocation ); showDialog(DLG_PROGRESS); locationLookup.locateStations(); - stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000); + stationsFetched.sendEmptyMessageDelayed(0, 500); } - void startNameSearch(String name) { - dialogMessage = getString( stationlist_findbyname ); - showDialog(DLG_PROGRESS); - - findStationsTask = new FindStationsTask(); - findStationsTask.searchByName(name, locationLookup.getLocation()); - findStationsTask.execute(); + void startNameLookup(String name) { + stations = stationProvider.lookupStationsByName(name); + getListView().invalidateViews(); + adapter.setStations( stations ); } public void startFavoriteLookup() { if (favorites.size() > 0) { - dialogMessage = getString( stationlist_loadfavorites ); - showDialog(DLG_PROGRESS); - - findStationsTask = new FindStationsTask(); - findStationsTask.searchByIds(favorites.toString(), locationLookup.getLocation()); - findStationsTask.execute(); + + stations = stationProvider.lookupStationsByIds( favorites.toString() ); + getListView().invalidateViews(); + adapter.setStations( stations ); + + } else { showMessageAndClose( getString( stationlist_nofavorites ) ); } @@ -355,14 +409,11 @@ - void startLocatorTask() - { - dialogMessage = getString( stationlist_findingnearby ); - showDialog(DLG_PROGRESS); - - findStationsTask = new FindStationsTask(); - findStationsTask.searchByLocation( locationLookup.getLocation() ); - findStationsTask.execute(); + void startNearestLookupPhase2() + { + stations = stationProvider.lookupStationsByLocation( locationLookup.getLocation() ); + getListView().invalidateViews(); + adapter.setStations( stations ); } @@ -373,165 +424,73 @@ @Override public void handleMessage(Message msg) { - switch (msg.what) { + LocationLookup.LookupStates state = locationLookup.getState(); + + + switch (state) { case GOTLOCATION: dismissDialog(DLG_PROGRESS); - - startLocatorTask(); - location = GeoPair.fromLocation( locationLookup.getLocation() ); - - break; + + startNearestLookupPhase2(); + + return; case NOPROVIDER: dismissDialog(DLG_PROGRESS); - MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider) ); - 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( getString( stationlist_gpstimeout) ); - builder.setCancelable(true); - builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - startLookup(); - - } - }); - builder.setNegativeButton( getString(generic_cancel), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }); - builder.show(); - - } - } - break; + 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; + } - 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) { - 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) { - - 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); - } - } + if (locationLookup.elapsedTime() >= GPS_TIMEOUT_MS) { + dismissDialog(DLG_PROGRESS); - } - - return null; - } - @Override - protected void onPostExecute(Void result) { - super.onPostExecute(result); - dialog.dismiss(); - - - if (success) { - if (stationProvider.getStations().size() == 0) { - showMessageAndClose(getString(stationlist_nostations)); + locationLookup.stopSearch(); + + if (locationLookup.hasLocation()) { + startNearestLookupPhase2(); + } 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(); + } - stations = stationProvider.getStations(); - adapter.setStations( stations ); - - } else { //communication or parse errors - AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this); - builder.setMessage(getString(stationlist_nearbyerror)); - builder.setCancelable(true); - 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(); - } - }); - } - }); - builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }); - builder.show(); + } 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); } + } } - + + + class FavoritesMenu implements OnCreateContextMenuListener { private final static int FAVORITES_ADD = 9001; @@ -545,7 +504,7 @@ AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; selectedPosition = info.position; - int stationID = stations.get(selectedPosition).getId(); + int stationID = stations.entries.get(selectedPosition).getId(); if (!favorites.contains(stationID)) { menu.add(0, FAVORITES_ADD, 0, getString(stationlist_addfavorite) ); @@ -556,7 +515,7 @@ } public void onContextItemSelected(MenuItem item) { - StationBean sb = stations.get(selectedPosition); + StationEntry sb = stations.entries.get(selectedPosition); int stationID = sb.getId(); if (item.getItemId() == FAVORITES_ADD) { @@ -569,7 +528,7 @@ if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) { - stations.remove(selectedPosition); + stations.entries.remove(selectedPosition); adapter.notifyDataSetChanged(); } }