/[projects]/android/TrainInfo/src/dk/thoerup/traininfo/StationList.java
ViewVC logotype

Diff of /android/TrainInfo/src/dk/thoerup/traininfo/StationList.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 555 by torben, Wed Jan 27 06:07:27 2010 UTC revision 1577 by torben, Sun Jul 10 07:45:38 2011 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfo;  package dk.thoerup.traininfo;
2    
3  import java.util.ArrayList;  import static dk.thoerup.traininfo.R.string.app_name;
4  import java.util.List;  import static dk.thoerup.traininfo.R.string.generic_cancel;
5    import static dk.thoerup.traininfo.R.string.generic_retry;
6    import static dk.thoerup.traininfo.R.string.stationlist_accuracy;
7    import static dk.thoerup.traininfo.R.string.stationlist_addfavorite;
8    import static dk.thoerup.traininfo.R.string.stationlist_favorites;
9    import static dk.thoerup.traininfo.R.string.stationlist_gpsinfo;
10    import static dk.thoerup.traininfo.R.string.stationlist_gpstimeout;
11    import static dk.thoerup.traininfo.R.string.stationlist_latitude;
12    import static dk.thoerup.traininfo.R.string.stationlist_locationinfo;
13    import static dk.thoerup.traininfo.R.string.stationlist_longitude;
14    import static dk.thoerup.traininfo.R.string.stationlist_nearbystations;
15    import static dk.thoerup.traininfo.R.string.stationlist_nofavorites;
16    import static dk.thoerup.traininfo.R.string.stationlist_nolocationprovider;
17    import static dk.thoerup.traininfo.R.string.stationlist_obtainedby;
18    import static dk.thoerup.traininfo.R.string.stationlist_removefavorite;
19    import static dk.thoerup.traininfo.R.string.stationlist_satellitecount;
20    import static dk.thoerup.traininfo.R.string.stationlist_search;
21    import static dk.thoerup.traininfo.R.string.stationlist_stationadded;
22    import static dk.thoerup.traininfo.R.string.stationlist_stationmap;
23    import static dk.thoerup.traininfo.R.string.stationlist_stationremoved;
24    import static dk.thoerup.traininfo.R.string.stationlist_waitforlocation;
25    
26    import java.util.ArrayList;
27    
28    import android.app.Activity;
29  import android.app.AlertDialog;  import android.app.AlertDialog;
30  import android.app.Dialog;  import android.app.Dialog;
31  import android.app.ListActivity;  import android.app.ListActivity;
# Line 13  import android.content.Intent; Line 35  import android.content.Intent;
35  import android.content.SharedPreferences;  import android.content.SharedPreferences;
36  import android.content.SharedPreferences.Editor;  import android.content.SharedPreferences.Editor;
37  import android.location.Location;  import android.location.Location;
 import android.os.AsyncTask;  
38  import android.os.Bundle;  import android.os.Bundle;
39  import android.os.Handler;  import android.os.Handler;
40  import android.os.Message;  import android.os.Message;
41    import android.text.Editable;
42    import android.text.TextWatcher;
43    import android.util.Log;
44  import android.view.ContextMenu;  import android.view.ContextMenu;
45  import android.view.LayoutInflater;  import android.view.ContextMenu.ContextMenuInfo;
46  import android.view.Menu;  import android.view.Menu;
47  import android.view.MenuItem;  import android.view.MenuItem;
48  import android.view.View;  import android.view.View;
 import android.view.ContextMenu.ContextMenuInfo;  
49  import android.view.View.OnCreateContextMenuListener;  import android.view.View.OnCreateContextMenuListener;
50  import android.widget.AdapterView;  import android.widget.AdapterView;
 import android.widget.EditText;  
51  import android.widget.ListView;  import android.widget.ListView;
52    import android.widget.TextView;
53  import android.widget.Toast;  import android.widget.Toast;
54    import dk.thoerup.android.traininfo.common.StationBean;
55    import dk.thoerup.android.traininfo.common.StationEntry;
56    import dk.thoerup.traininfo.WelcomeScreen.ListType;
57  import dk.thoerup.traininfo.provider.ProviderFactory;  import dk.thoerup.traininfo.provider.ProviderFactory;
58  import dk.thoerup.traininfo.provider.StationProvider;  import dk.thoerup.traininfo.provider.StationProvider;
59  import dk.thoerup.traininfo.stationmap.GeoPair;  import dk.thoerup.traininfo.stationmap.GeoPair;
# Line 37  import dk.thoerup.traininfo.util.IntSet; Line 62  import dk.thoerup.traininfo.util.IntSet;
62  import dk.thoerup.traininfo.util.MessageBox;  import dk.thoerup.traininfo.util.MessageBox;
63    
64  public class StationList extends ListActivity  {  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;  
65    
66                    
67            
68            public static final int OPTIONS_MAP = 103;
69            public static final int OPTIONS_GPSINFO = 104;
70                    
71          public static final int DLG_PROGRESS = 3001;          public static final int DLG_PROGRESS = 3001;
72          public static final int DLG_STATIONNAME = 3002;          
73            
74            public static final int GPS_TIMEOUT_MS = 15000; //how long are we willing to wait for gps fix -in milliseconds
75            
76                    
77          static enum LookupMethod {          static enum LookupMethod {
78                  ByLocation,                  ByLocation,
# Line 62  public class StationList extends ListAct Line 85  public class StationList extends ListAct
85          String dialogMessage = "";          String dialogMessage = "";
86          ProgressDialog dialog;          ProgressDialog dialog;
87          LocationLookup locationLookup = null;          LocationLookup locationLookup = null;
         FindStationsTask findStationsTask;  
88          StationsFetchedHandler stationsFetched = new StationsFetchedHandler();          StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
89                    
90          GeoPair location = new GeoPair();          //GeoPair location = new GeoPair();
91            
92          boolean isRunning = false;          boolean isLaunchedforShortcut;
93          List<StationBean> stations = new ArrayList<StationBean>();  
94            StationBean stations = new StationBean();
95                    
96          StationProvider stationProvider = ProviderFactory.getStationProvider();          StationProvider stationProvider = ProviderFactory.getStationProvider();
97                                    
# Line 79  public class StationList extends ListAct Line 102  public class StationList extends ListAct
102    
103          WelcomeScreen.ListType listType;          WelcomeScreen.ListType listType;
104          SharedPreferences prefs;          SharedPreferences prefs;
105                                    
106          ///////////////////////////////////////////////////////////////////////////////////////////          ///////////////////////////////////////////////////////////////////////////////////////////
107          //Activity call backs          //Activity call backs
108                    
109          @SuppressWarnings("unchecked")  
110          @Override          @Override
111          public void onCreate(Bundle savedInstanceState) {          public void onCreate(Bundle savedInstanceState) {
112                  super.onCreate(savedInstanceState);                  super.onCreate(savedInstanceState);
113                  setContentView(R.layout.stationlist);                  setContentView(R.layout.stationlist);
114                                    
115                    listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type");
116                                    
117                  adapter = new StationListAdapter(this);                  adapter = new StationListAdapter(this, (listType == ListType.ListNearest) );
118                  setListAdapter(adapter);                  setListAdapter(adapter);
119                                    
120                  ListView lv = getListView();                  ListView lv = getListView();
121                  lv.setOnCreateContextMenuListener(contextMenu);                  lv.setOnCreateContextMenuListener(contextMenu);
122                                    
123                  locationLookup = new LocationLookup(this, stationsFetched);                  locationLookup = new LocationLookup(this);
124                                    
125    
126                  prefs = getSharedPreferences("TrainStation", 0);                  prefs = getSharedPreferences("TrainStation", 0);
# Line 105  public class StationList extends ListAct Line 129  public class StationList extends ListAct
129                          favorites.fromString(favoriteString);                          favorites.fromString(favoriteString);
130                  }                  }
131                                    
                 listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type");  
132                  setTitle();                  setTitle();
133                                    
134                    isLaunchedforShortcut = getIntent().getBooleanExtra("shortcut", false);
135                    
136                    ProviderFactory.purgeOldEntries(); //cleanup before fetching more data
137                    
138                    if (listType == ListType.ListSearch) {
139                            enableNamesearchField();
140                    }
141                    
142                  if (savedInstanceState == null) {                  if (savedInstanceState == null) {
143                    
                           
144                          switch (listType) {                          switch (listType) {
145                          case ListNearest:                          case ListNearest:
146                                  startLookup();                                  startNearestLookup();
147                                  break;                                  break;
148                          case ListSearch:                          case ListSearch:                                
149                                  this.showDialog(DLG_STATIONNAME);                                  // do nothing here
150                                  break;                                  break;
151                          case ListFavorites:                          case ListFavorites:
152                                  startFavoriteLookup();                                  startFavoriteLookup();
# Line 126  public class StationList extends ListAct Line 156  public class StationList extends ListAct
156                          }                          }
157                                                    
158                  } else {                  } else {
159                          stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");                          ((TextView)findViewById(R.id.stationsearch)).setText(  savedInstanceState.getString( "search") );
160                            
161                            stations = (StationBean) savedInstanceState.getSerializable("stations");
162                          adapter.setStations(stations);                          adapter.setStations(stations);
                         location = (GeoPair) savedInstanceState.getSerializable("location");  
163                  }                  }
164                                    
165          }          }
166            
167            
168    
169    
170    
171    
172            @Override
173            protected void onDestroy() {
174                    super.onDestroy();
175                    
176                    stationsFetched.removeMessages(0);
177                    
178                    
179                    if (locationLookup != null) {
180                            locationLookup.stopSearch();
181                    }
182            
183            }
184    
185            
186          protected void setTitle() {          protected void setTitle() {
187                  String dialogTitle = getResources().getString(R.string.app_name);                  String dialogTitle = getResources().getString(app_name);
188                  switch (listType) {                  switch (listType) {
189                  case ListNearest:                  case ListNearest:
190                          dialogTitle += " - Nearby stations";                          dialogTitle += " - " + getString(stationlist_nearbystations);
191                          break;                          break;
192                  case ListSearch:                  case ListSearch:
193                          dialogTitle += " - Search";                          dialogTitle += " - " + getString(stationlist_search);
194                          break;                          break;
195                  case ListFavorites:                  case ListFavorites:
196                          dialogTitle += " - Favorites";                          dialogTitle += " - " + getString(stationlist_favorites);
197                          break;                          break;
198                  default:                  default:
199                          dialogTitle = "";//not possible                                                          dialogTitle = "";//not possible                                
200                  }                  }
201                    
202                  setTitle(dialogTitle);                  setTitle(dialogTitle);
203                    
204          }          }
205                    
206                    
207            public void enableNamesearchField() {
208                    final TextView stationSearch = (TextView) findViewById(R.id.stationsearch);
209                    stationSearch.setVisibility( View.VISIBLE );
210                    stationSearch.addTextChangedListener( new TextWatcher() {
211    
212                            @Override
213                            public void afterTextChanged(Editable s) {
214                                    if (s.length() > 0) {
215                                            startNameLookup( s.toString() );
216                                    } else {
217                                            stations = new StationBean();
218                                            getListView().invalidateViews();
219                                            adapter.setStations( stations );        
220                                    }
221                            }
222    
223                            @Override
224                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
225                            }
226    
227                            @Override
228                            public void onTextChanged(CharSequence s, int start, int before, int count) {
229                            }
230                            
231                    });
232                    
233                    
234            }
235                    
236    
237      @Override      @Override
238      public void onSaveInstanceState(Bundle outState)      public void onSaveInstanceState(Bundle outState)
239      {      {
240          if (dialog != null && dialog.isShowing())          if (dialog != null && dialog.isShowing())
241                  dialog.dismiss();                  dialog.dismiss();
242          outState.putSerializable("stations", (ArrayList<StationBean>) stations);          outState.putSerializable("stations", (StationBean) stations);
243          outState.putSerializable("location", location);          outState.putString("search", ((TextView)findViewById(R.id.stationsearch)).getText().toString() );
244                    
245      }      }
246                    
# Line 169  public class StationList extends ListAct Line 249  public class StationList extends ListAct
249          @Override          @Override
250          public boolean onCreateOptionsMenu(Menu menu) {          public boolean onCreateOptionsMenu(Menu menu) {
251                  MenuItem item;                  MenuItem item;
252                                                    
253                  item = menu.add(0, OPTIONS_MAP, 0, "Station map");                  item = menu.add(0, OPTIONS_MAP, 0, getString(stationlist_stationmap));
254                  item.setIcon(android.R.drawable.ic_menu_mapmode);                  item.setIcon(android.R.drawable.ic_menu_mapmode);
255                                    
256                  item = menu.add(0, OPTIONS_GPSINFO, 0, "GPS Info");                  item = menu.add(0, OPTIONS_GPSINFO, 0, getString(stationlist_gpsinfo));
257                  item.setIcon(android.R.drawable.ic_menu_mapmode);                                item.setIcon(android.R.drawable.ic_menu_info_details);
258                    boolean hasLoc = (locationLookup.getLocation() != null);
259                    item.setEnabled(hasLoc);
260                                    
261                  return true;                  return true;
262          }          }
263            
264    
265    
266    
267          @Override          @Override
268          public boolean onOptionsItemSelected(MenuItem item) {          public boolean onOptionsItemSelected(MenuItem item) {
269                  boolean retval = true;                  boolean retval = true;
270    
271                  //TODO: Cleanup  
272                  switch (item.getItemId()) {                  switch (item.getItemId()) {
273                  case OPTIONS_MAP:                  case OPTIONS_MAP:
274                                                    
275                            if ( stations == null || stations.entries == null || stations.entries.size() == 0 ) {
276                                    Toast.makeText(this, "No stations to show on map", Toast.LENGTH_SHORT).show(); //TODO: Translate
277                                    return true;
278                            }
279                            
280                          Intent intent = new Intent(this,StationMapView.class);                          Intent intent = new Intent(this,StationMapView.class);
281                                                    
282                          ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();                          ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
283                          for (StationBean st : stations ) {                          for (StationEntry st : stations.entries ) {
284                                  stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );                                  stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
285                          }                          }
286                                                    
# Line 201  public class StationList extends ListAct Line 291  public class StationList extends ListAct
291                  case OPTIONS_GPSINFO:                  case OPTIONS_GPSINFO:
292                          Location loc = locationLookup.getLocation();                          Location loc = locationLookup.getLocation();
293                          StringBuffer message = new StringBuffer();                          StringBuffer message = new StringBuffer();
294                          message.append("Location info:\n");                          message.append( getString(stationlist_locationinfo) ).append(":\n");
295                          if (loc != null) {                          
296                                  message.append("-Obtained by: ").append( loc.getProvider() ).append("\n");                          message.append( getString(stationlist_obtainedby) ).append( loc.getProvider() ).append("\n");
297                                  message.append("-Accuracy: ").append( (int)loc.getAccuracy()).append("m\n");                          message.append( getString(stationlist_accuracy) ).append( (int)loc.getAccuracy()).append("m\n");
298                                  message.append("-Latitude: ").append( loc.getLatitude()).append("\n");                          message.append( getString(stationlist_latitude) ).append( (float)loc.getLatitude()).append("\n");
299                                  message.append("-Longitude: ").append( loc.getLongitude() ).append("\n");                          message.append( getString(stationlist_longitude) ).append( (float)loc.getLongitude() ).append("\n");
300                          } else {                                                  
301                                  message.append(" - No location data!");                          
302                          }                          MessageBox.showMessage(this, message.toString(), false);
                                   
                         MessageBox.showMessage(this, message.toString());  
303                          break;                          break;
304                  default:                  default:
305                          retval = super.onOptionsItemSelected(item);                          retval = super.onOptionsItemSelected(item);
# Line 229  public class StationList extends ListAct Line 317  public class StationList extends ListAct
317    
318    
319          }          }
320            
321            public void showMessageAndClose(String message) {
322                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
323                    builder.setMessage(message)
324                    .setCancelable(false)
325                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
326                            public void onClick(DialogInterface dialog, int id) {
327                                    dialog.dismiss();
328                                    StationList.this.finish();
329                            }
330                    })
331                    .show();
332            }
333    
334    
335    
# Line 238  public class StationList extends ListAct Line 339  public class StationList extends ListAct
339                  switch (id) {                  switch (id) {
340                  case DLG_PROGRESS:                  case DLG_PROGRESS:
341                          ProgressDialog dlg = new ProgressDialog(this);                          ProgressDialog dlg = new ProgressDialog(this);
342                          dlg.setMessage("Wait for location fix");                          dlg.setMessage( getString(stationlist_waitforlocation) );
343                          dlg.setCancelable(false);                          dlg.setCancelable(false);
344                          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();  
                                         StationList.this.finish(); // Close this Activity  
                                 }  
                         });                      
                         return builder.create();  
345                                                    
346                  default:                  default:
347                          return super.onCreateDialog(id);                                          return super.onCreateDialog(id);                
# Line 295  public class StationList extends ListAct Line 368  public class StationList extends ListAct
368          protected void onListItemClick(ListView l, View v, int position, long id) {          protected void onListItemClick(ListView l, View v, int position, long id) {
369                  super.onListItemClick(l, v, position, id);                  super.onListItemClick(l, v, position, id);
370                                                                    
371                  StationBean station = stations.get(position);                  StationEntry station = stations.entries.get(position);
   
                 double latitude = station.getLatitude();  
                 double longitude = station.getLongitude();  
   
   
372                                    
373                  Intent intent = new Intent(this, DepartureList.class);                  if (isLaunchedforShortcut == true) {
374                  intent.putExtra("name", station.getName());                          Intent i = new Intent();
375                  intent.putExtra("distance", station.getDistance());                          i.putExtra("station", station);
376                  intent.putExtra("latitude", latitude);                          setResult(Activity.RESULT_OK, i);
377                  intent.putExtra("longitude", longitude);                          finish();
378                  intent.putExtra("stationid", station.getId());                  } else {                
379                  intent.putExtra("address", station.getAddress());                          Intent intent = new Intent(this, DepartureList.class);
380                  intent.putExtra("isregional", station.isRegional());                          intent.putExtra("stationbean", station);
381                  intent.putExtra("isstrain", station.isSTrain());                          startActivity(intent);
382                  intent.putExtra("ismetro", station.isMetro());                  }
                 startActivity(intent);  
383          }          }
384    
385          /////////////////////////////////////////////////////////////          /////////////////////////////////////////////////////////////
386          //          //
387    
388          public void startLookup() {          public void startNearestLookup() {
389                  isRunning = true;                  dialogMessage = getString( stationlist_waitforlocation );
                 dialogMessage = "Wait for location fix";  
390                  showDialog(DLG_PROGRESS);                  showDialog(DLG_PROGRESS);
391                                    
392                  locationLookup.locateStations();                  locationLookup.locateStations();
393                  stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000);                  stationsFetched.sendEmptyMessageDelayed(0, 500);
394          }          }
395                    
396          void startNameSearch(String name) {          void startNameLookup(String name) {
                 dialogMessage = "Finding stations by name";  
                 showDialog(DLG_PROGRESS);  
   
                 findStationsTask = new FindStationsTask();  
                 findStationsTask.searchByName(name, locationLookup.getLocation());  
                 findStationsTask.execute();  
397                                    
398                    stations = stationProvider.lookupStationsByName(name);
399                    getListView().invalidateViews();
400                    adapter.setStations( stations );                                
401          }          }
402                    
403          public void startFavoriteLookup() {          public void startFavoriteLookup() {
404                                    
405                  if (favorites.size() > 0) {                  if (favorites.size() > 0) {
406                          dialogMessage = "Loading favorites";                          
407                          showDialog(DLG_PROGRESS);                          stations = stationProvider.lookupStationsByIds( favorites.toString() );
408                            getListView().invalidateViews();
409                          findStationsTask = new FindStationsTask();                          adapter.setStations( stations );                
410                          findStationsTask.searchByIds(favorites.toString(), locationLookup.getLocation());                          
411                          findStationsTask.execute();                          
412                  } else {                  } else {
413                          MessageBox.showMessage(this, "Favorite list is empty");                          showMessageAndClose( getString( stationlist_nofavorites ) );
414                  }                  }
415          }          }
416    
417    
418                    
419          void startLocatorTask()          void startNearestLookupPhase2()
420          {          {      
421                  dialogMessage = "Finding nearby stations";                  stations = stationProvider.lookupStationsByLocation( locationLookup.getLocation() );
422                  showDialog(DLG_PROGRESS);                  getListView().invalidateViews();
423                                    adapter.setStations( stations );
                 findStationsTask = new FindStationsTask();  
                 findStationsTask.searchByLocation( locationLookup.getLocation() );  
                 findStationsTask.execute();      
424          }          }
           
   
         /* TODO: Remove this no longer needed function  
         String lookupAddress(double latitude, double longitude) {  
425                                    
                 Geocoder coder = new Geocoder(this, new Locale("da"));  
                 StringBuilder sb = new StringBuilder();  
                 Log.i("lookupaddr", "" + latitude + "/" + longitude);  
                 try {  
                         List<Address> addressList = coder.getFromLocation(latitude, longitude, 1);  
                         Address addr = addressList.get(0);  
                           
                           
                         int max = addr.getMaxAddressLineIndex();  
                         for (int i=0; i<max; i++) {  
                                 if (i>0)  
                                         sb.append(", ");  
                                   
                                 sb.append(addr.getAddressLine(i));  
                         }  
                           
                           
                 } catch (Exception e) {  
                         Log.e("DepartureList", "geocoder failed", e);  
                 }  
                   
                 return sb.toString();  
         }*/  
           
426                    
427          ////////////////////////////////////////////////////////////////////////////          ////////////////////////////////////////////////////////////////////////////
428          // Inner classes          // Inner classes
# Line 399  public class StationList extends ListAct Line 431  public class StationList extends ListAct
431                  @Override                  @Override
432                  public void handleMessage(Message msg) {                  public void handleMessage(Message msg) {
433    
434                          switch (msg.what) {                          LocationLookup.LookupStates state = locationLookup.getState();
435    
436    
437                            switch (state) {
438                          case GOTLOCATION:                          case GOTLOCATION:
439                                  dismissDialog(DLG_PROGRESS);                                  dismissDialog(DLG_PROGRESS);
440                                    
441                                  startLocatorTask();                                  startNearestLookupPhase2();
442                                  location = GeoPair.fromLocation( locationLookup.getLocation() );  
443                                                                    return;
                                 break;  
444    
445                          case NOPROVIDER:                          case NOPROVIDER:
446                                  dismissDialog(DLG_PROGRESS);                                  dismissDialog(DLG_PROGRESS);
447                                  MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps.");                                  MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider), true );
448                                  break;                                  //StationList.this.finish();
449                          case LOCATIONFIXTIMEOUT:                                                                  return;
450                                  if (isRunning) {                          case IDLE:
451                                          locationLookup.stopSearch();                                  Log.e("TrainInfo", "How did this happen ???");
452                                          if (locationLookup.hasLocation()) {                                  dismissDialog(DLG_PROGRESS); // how did we get here ??
453                                                  stationsFetched.sendEmptyMessage( GOTLOCATION );                                  return;
454                                          } 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;  
455                          }                          }
                         isRunning = false;  
                 }  
         };  
456    
           
         class FindStationsTask extends AsyncTask<Void,Void,Void> {  
                   
                 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() {  
457    
                         if (method.equals(LookupMethod.MethodNone))  
                                 throw new RuntimeException("Method not set");  
                         super.onPreExecute();  
                 }  
                   
                 @Override  
                 protected Void doInBackground(Void... params) {  
458    
459                          switch (method) {                          if (locationLookup.elapsedTime() >=  GPS_TIMEOUT_MS) {
460                          case ByLocation:                                  dismissDialog(DLG_PROGRESS);
                                 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<StationBean> 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);  
                                         }  
                                 }  
461    
                         }                                                
                           
                         return null;  
                 }  
462    
463                  @Override                                  locationLookup.stopSearch();
464                  protected void onPostExecute(Void result) {  
465                          super.onPostExecute(result);                                  if (locationLookup.hasLocation()) {
466                          dialog.dismiss();                                          startNearestLookupPhase2();
467                                                            } else {                                                
468                                                                    AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                
469                          if (success) {                                                                    builder.setMessage(  getString( stationlist_gpstimeout) );
470                                  if (stationProvider.getStations().size() == 0)                                          builder.setCancelable(true);
471                                          MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?!                                          builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
472                                  stations = stationProvider.getStations();                                                  public void onClick(DialogInterface dialog, int id) {
473                                  adapter.setStations( stations );                                                                                          dialog.dismiss();
474                                                                                            startNearestLookup();
475                          } else { //communication or parse errors  
476                                  AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                                                                  }
477                                  builder.setMessage("Error on finding nearby stations");                                          });
478                                  builder.setCancelable(true);                                          builder.setNegativeButton( getString(generic_cancel), new DialogInterface.OnClickListener() {
479                                  builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {                                                  public void onClick(DialogInterface dialog, int id) {
480                                          public void onClick(DialogInterface dialog, int id) {                                                          dialog.dismiss();
481                                                  dialog.dismiss();                                                          StationList.this.finish(); // Close this Activity
482                                                                                                    }                                                      
483                                                  stationsFetched.post( new Runnable() {                                          });
484                                                          @Override                                          builder.show();
485                                                          public void run() {  
486                                                                  startLocatorTask();                                                                                              }
487                                                          }                          } else {
488                                                  });                                  if (locationLookup.hasGps()) {
489                                          }                                          int count = locationLookup.getSatCount();
490                                  });                                          String dialogMessage = getString( stationlist_waitforlocation ) + "\n" + getString( stationlist_satellitecount ) + ": " + count;
491                                  builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {                                          dialog.setMessage( dialogMessage );
492                                          public void onClick(DialogInterface dialog, int id) {                                  }
493                                                  dialog.dismiss();                                  this.sendEmptyMessageDelayed(0, 500);
                                         }                                                        
                                 });                                                                                              
                                 builder.show();                          
494                          }                          }
495                            
496                  }                  }
497          }          }
498            
499    
500    
501                    
502          class FavoritesMenu implements OnCreateContextMenuListener {          class FavoritesMenu implements OnCreateContextMenuListener {
503                  private final static int FAVORITES_ADD = 9001;                  private final static int FAVORITES_ADD = 9001;
# Line 570  public class StationList extends ListAct Line 511  public class StationList extends ListAct
511                                                                                                    
512                          AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;                          AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
513                          selectedPosition = info.position;                          selectedPosition = info.position;
514                          int stationID = stations.get(selectedPosition).getId();                          int stationID = stations.entries.get(selectedPosition).getId();
515    
516                          if (!favorites.contains(stationID)) {                          if (!favorites.contains(stationID)) {
517                                  menu.add(0, FAVORITES_ADD, 0, "Add to favorites");                                  menu.add(0, FAVORITES_ADD, 0, getString(stationlist_addfavorite) );
518                          } else {                          } else {
519                                  menu.add(0, FAVORITES_REMOVE, 0, "Remove from favorites");                                  menu.add(0, FAVORITES_REMOVE, 0, getString(stationlist_removefavorite) );
520                          }                          }
521                                                    
522                  }                  }
523                                    
524                  public void onContextItemSelected(MenuItem item) {                  public void onContextItemSelected(MenuItem item) {
525                          StationBean sb = stations.get(selectedPosition);                          StationEntry sb = stations.entries.get(selectedPosition);
526                                                    
527                          int stationID = sb.getId();                          int stationID = sb.getId();
528                          if (item.getItemId() == FAVORITES_ADD) {                          if (item.getItemId() == FAVORITES_ADD) {
529                                  favorites.add(stationID);                                  favorites.add(stationID);
530                                  Toast.makeText(StationList.this, "Station added", Toast.LENGTH_SHORT).show();                                  Toast.makeText(StationList.this, getString(stationlist_stationadded), Toast.LENGTH_SHORT).show();
531                          } else {                          } else {
532                                                                    
533                                  favorites.remove(stationID);                                  favorites.remove(stationID);
534                                  Toast.makeText(StationList.this, "Station removed", Toast.LENGTH_SHORT).show();                                  Toast.makeText(StationList.this, getString(stationlist_stationremoved), Toast.LENGTH_SHORT).show();
535                                                                    
536                                                                    
537                                  if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) {                                  if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) {
538                                          stations.remove(selectedPosition);                                          stations.entries.remove(selectedPosition);
539                                          adapter.notifyDataSetChanged();                                          adapter.notifyDataSetChanged();
540                                  }                                  }
541                          }                          }

Legend:
Removed from v.555  
changed lines
  Added in v.1577

  ViewVC Help
Powered by ViewVC 1.1.20