package dk.thoerup.traininfo; import java.util.ArrayList; import java.util.List; 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.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.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; 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 DLG_PROGRESS = 3001; public static final int DLG_STATIONNAME = 3002; public static final int GPS_TIMEOUT_MS = 17500; //how long are we willing to wait for gps fix -in milliseconds static enum LookupMethod { ByLocation, ByName, ByList, MethodNone } String dialogMessage = ""; ProgressDialog dialog; LocationLookup locationLookup = null; FindStationsTask findStationsTask; StationsFetchedHandler stationsFetched = new StationsFetchedHandler(); GeoPair location = new GeoPair(); boolean isLaunchedforShortcut; 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 @SuppressWarnings("unchecked") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.stationlist); adapter = new StationListAdapter(this); setListAdapter(adapter); 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(); isLaunchedforShortcut = getIntent().getBooleanExtra("shortcut", false); if (savedInstanceState == null) { switch (listType) { case ListNearest: startLookup(); break; case ListSearch: showDialog(DLG_STATIONNAME); //TODO: 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"); } } @Override protected void onDestroy() { super.onDestroy(); if (findStationsTask != null) { findStationsTask.cancel(true); } if (locationLookup != null) { locationLookup.stopSearch(); } isRunning = false; } 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 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, 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 = true; //TODO: Cleanup switch (item.getItemId()) { case OPTIONS_MAP: Intent intent = new Intent(this,StationMapView.class); 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( 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); } 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( 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) { startNameSearch(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); } } @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; } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); StationBean station = stations.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; dialogMessage = getString( stationlist_waitforlocation ); showDialog(DLG_PROGRESS);//TODO:showDialogSafe(DLG_PROGRESS); locationLookup.locateStations(); stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, GPS_TIMEOUT_MS); } void startNameSearch(String name) { dialogMessage = getString( stationlist_findbyname ); showDialog(DLG_PROGRESS);//TODO:showDialogSafe(DLG_PROGRESS); findStationsTask = new FindStationsTask(); findStationsTask.searchByName(name); findStationsTask.execute(); } public void startFavoriteLookup() { if (favorites.size() > 0) { dialogMessage = getString( stationlist_loadfavorites ); showDialog(DLG_PROGRESS);//TODO:showDialogSafe(DLG_PROGRESS); findStationsTask = new FindStationsTask(); findStationsTask.searchByIds( favorites.toString() ); findStationsTask.execute(); } else { showMessageAndClose( getString( stationlist_nofavorites ) ); } } void startLocatorTask() { dialogMessage = getString( stationlist_findingnearby ); showDialog(DLG_PROGRESS);//TODO:showDialogSafe(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) { case GOTLOCATION: dismissDialog(DLG_PROGRESS);//TODO:dismissDialogSafe(DLG_PROGRESS); startLocatorTask(); location = GeoPair.fromLocation( locationLookup.getLocation() ); break; case NOPROVIDER: dismissDialog(DLG_PROGRESS);//TODO:dismissDialogSafe(DLG_PROGRESS); MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider), true ); //StationList.this.finish(); break; case LOCATIONFIXTIMEOUT: if (isRunning) { locationLookup.stopSearch(); if (locationLookup.hasLocation()) { stationsFetched.sendEmptyMessage( GOTLOCATION ); } else { dismissDialog(DLG_PROGRESS);//TODO:dismissDialogSafe(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();//TODO:builderShowSafe(builder); } } break; } isRunning = false; } }; class FindStationsTask extends AsyncTask { LookupMethod method = LookupMethod.MethodNone; String name; Location loc; String ids; 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) { method = LookupMethod.ByList; 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: stations = stationProvider.lookupStations(loc); break; case ByName: stations = stationProvider.lookupStationsByName(name); break; case ByList: stations = stationProvider.lookupStationsByIds(ids); break; default: stations = null; // not possible } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); dialog.dismiss();//TODO:dismissDialogSafe(dialog); if (stations != null) { if (stations.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(getString(stationlist_fetcherror)); builder.setCancelable(true); builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); 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(getString(generic_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); StationList.this.finish(); } }); builder.show();//TODO:builderShowSafe(builder); } } } 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, getString(stationlist_addfavorite) ); } else { menu.add(0, FAVORITES_REMOVE, 0, getString(stationlist_removefavorite) ); } } 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, 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.remove(selectedPosition); adapter.notifyDataSetChanged(); } } Editor ed = prefs.edit(); ed.putString("favorites", favorites.toString()); ed.commit(); } } }