/[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 441 by torben, Sun Oct 11 07:23:35 2009 UTC revision 1576 by torben, Sun Jul 10 07:18:54 2011 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfo;  package dk.thoerup.traininfo;
2    
3    import static dk.thoerup.traininfo.R.string.app_name;
4    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;  import java.util.ArrayList;
 import java.util.List;  
 import java.util.Locale;  
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 12  import android.content.DialogInterface; Line 34  import android.content.DialogInterface;
34  import android.content.Intent;  import android.content.Intent;
35  import android.content.SharedPreferences;  import android.content.SharedPreferences;
36  import android.content.SharedPreferences.Editor;  import android.content.SharedPreferences.Editor;
 import android.location.Address;  
 import android.location.Geocoder;  
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;  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 39  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_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;  
           
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 65  public class StationList extends ListAct Line 84  public class StationList extends ListAct
84                    
85          String dialogMessage = "";          String dialogMessage = "";
86          ProgressDialog dialog;          ProgressDialog dialog;
87          LocationLookup locator = 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 80  public class StationList extends ListAct Line 99  public class StationList extends ListAct
99                    
100          FavoritesMenu contextMenu = new FavoritesMenu();          FavoritesMenu contextMenu = new FavoritesMenu();
101          IntSet favorites = new IntSet();          IntSet favorites = new IntSet();
           
102    
103                    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.main);                  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                  locator = new LocationLookup(this, stationsFetched);                  locationLookup = new LocationLookup(this);
124                                    
125    
126                  prefs = getSharedPreferences("TrainStation", 0);                  prefs = getSharedPreferences("TrainStation", 0);
# Line 110  public class StationList extends ListAct Line 129  public class StationList extends ListAct
129                          favorites.fromString(favoriteString);                          favorites.fromString(favoriteString);
130                  }                  }
131                                    
132                    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                          startLookup();                  
144                            switch (listType) {
145                            case ListNearest:
146                                    startNearestLookup();
147                                    break;
148                            case ListSearch:                                
149                                    // do nothing here
150                                    break;
151                            case ListFavorites:
152                                    startFavoriteLookup();
153                                    break;
154                            default:
155                                    // Not possible !?!
156                            }
157                            
158                  } else {                  } else {
159                          stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");                          stations = (StationBean) savedInstanceState.getSerializable("stations");
160                          adapter.setStations(stations);                          adapter.setStations(stations);
                         location = (GeoPair) savedInstanceState.getSerializable("location");  
161                  }                  }
162                    
163            }
164            
165            
166    
167    
168    
169    
170            @Override
171            protected void onDestroy() {
172                    super.onDestroy();
173                    
174                    stationsFetched.removeMessages(0);
175                    
176                    
177                    if (locationLookup != null) {
178                            locationLookup.stopSearch();
179                    }
180            
181            }
182    
183            
184            protected void setTitle() {
185                    String dialogTitle = getResources().getString(app_name);
186                    switch (listType) {
187                    case ListNearest:
188                            dialogTitle += " - " + getString(stationlist_nearbystations);
189                            break;
190                    case ListSearch:
191                            dialogTitle += " - " + getString(stationlist_search);
192                            break;
193                    case ListFavorites:
194                            dialogTitle += " - " + getString(stationlist_favorites);
195                            break;
196                    default:
197                            dialogTitle = "";//not possible                                
198                    }
199            
200                    setTitle(dialogTitle);
201                    
202          }          }
203            
204            
205            public void enableNamesearchField() {
206                    final TextView stationSearch = (TextView) findViewById(R.id.stationsearch);
207                    stationSearch.setVisibility( View.VISIBLE );
208                    stationSearch.addTextChangedListener( new TextWatcher() {
209    
210                            @Override
211                            public void afterTextChanged(Editable s) {
212                                    if (s.length() > 0) {
213                                            startNameLookup( s.toString() );
214                                    } else {
215                                            stations = new StationBean();
216                                            getListView().invalidateViews();
217                                            adapter.setStations( stations );        
218                                    }
219                            }
220    
221                            @Override
222                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
223                            }
224    
225                            @Override
226                            public void onTextChanged(CharSequence s, int start, int before, int count) {
227                            }
228                            
229                    });
230                    
231                    
232            }
233                    
234    
235      @Override      @Override
236      public void onSaveInstanceState(Bundle outState)      public void onSaveInstanceState(Bundle outState)
237      {      {
238          if (dialog != null && dialog.isShowing())          if (dialog != null && dialog.isShowing())
239                  dialog.dismiss();                  dialog.dismiss();
240          outState.putSerializable("stations", (ArrayList<StationBean>) stations);          outState.putSerializable("stations", (StationBean) stations);
241          outState.putSerializable("location", location);          
242      }      }
243                    
244                    
# Line 135  public class StationList extends ListAct Line 247  public class StationList extends ListAct
247          public boolean onCreateOptionsMenu(Menu menu) {          public boolean onCreateOptionsMenu(Menu menu) {
248                  MenuItem item;                  MenuItem item;
249                                    
250                  item = menu.add(0, OPTIONS_RESCAN, 0, "Nearest stations");                  item = menu.add(0, OPTIONS_MAP, 0, getString(stationlist_stationmap));
                 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, "Station map");  
251                  item.setIcon(android.R.drawable.ic_menu_mapmode);                  item.setIcon(android.R.drawable.ic_menu_mapmode);
252                                    
253                  item = menu.add(0, OPTIONS_ABOUT, 0, "About");                  item = menu.add(0, OPTIONS_GPSINFO, 0, getString(stationlist_gpsinfo));
254                  item.setIcon(android.R.drawable.ic_menu_info_details);                  item.setIcon(android.R.drawable.ic_menu_info_details);
255                    boolean hasLoc = (locationLookup.getLocation() != null);
256                    item.setEnabled(hasLoc);
257                    
258                  return true;                  return true;
259          }          }
260            
261    
262    
263    
264          @Override          @Override
265          public boolean onOptionsItemSelected(MenuItem item) {          public boolean onOptionsItemSelected(MenuItem item) {
266                  boolean retval = true;                  boolean retval = true;
267    
268                    
269                  switch (item.getItemId()) {                  switch (item.getItemId()) {
                 case OPTIONS_RESCAN:  
                         startLookup();  
                         break;  
                 case OPTIONS_NAMESEARCH:  
                         showDialog(DLG_STATIONNAME);  
                         break;  
                 case OPTIONS_FAVORITES:  
                         startFavoriteLookup();  
                         break;  
270                  case OPTIONS_MAP:                  case OPTIONS_MAP:
271                                                    
272                            if ( stations == null || stations.entries == null || stations.entries.size() == 0 ) {
273                                    Toast.makeText(this, "No stations to show on map", Toast.LENGTH_SHORT).show(); //TODO: Translate
274                                    return true;
275                            }
276                            
277                          Intent intent = new Intent(this,StationMapView.class);                          Intent intent = new Intent(this,StationMapView.class);
                         intent.putExtra("userlocation", location );  
278                                                    
279                          ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();                          ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
280                          for (StationBean st : stations ) {                          for (StationEntry st : stations.entries ) {
281                                  stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );                                  stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
282                          }                          }
283                                                    
# Line 181  public class StationList extends ListAct Line 285  public class StationList extends ListAct
285                                                    
286                          startActivity(intent);                          startActivity(intent);
287                          break;                          break;
288                  case OPTIONS_ABOUT:                  case OPTIONS_GPSINFO:
289                          String ver = this.getResources().getString(R.string.app_version);                          Location loc = locationLookup.getLocation();
                           
                         Location loc = locator.getLocation();  
290                          StringBuffer message = new StringBuffer();                          StringBuffer message = new StringBuffer();
291                          message.append("TrainInfo DK v").append(ver).append("\n");                          message.append( getString(stationlist_locationinfo) ).append(":\n");
292                          message.append("By Torben Nielsen\n");                          
293                          message.append("\n");                          message.append( getString(stationlist_obtainedby) ).append( loc.getProvider() ).append("\n");
294                          message.append("Location info:\n");                          message.append( getString(stationlist_accuracy) ).append( (int)loc.getAccuracy()).append("m\n");
295                          message.append("-Obtained by: ").append(loc != null ? loc.getProvider() : "-").append("\n");                          message.append( getString(stationlist_latitude) ).append( (float)loc.getLatitude()).append("\n");
296                          message.append("-Accuracy: ").append(loc != null ? (int)loc.getAccuracy() : "-").append("m\n");                          message.append( getString(stationlist_longitude) ).append( (float)loc.getLongitude() ).append("\n");
297                                                    
298                          MessageBox.showMessage(this, message.toString());                          
299                            MessageBox.showMessage(this, message.toString(), false);
300                          break;                          break;
301                  default:                  default:
302                          retval = super.onOptionsItemSelected(item);                          retval = super.onOptionsItemSelected(item);
# Line 211  public class StationList extends ListAct Line 314  public class StationList extends ListAct
314    
315    
316          }          }
317            
318            public void showMessageAndClose(String message) {
319                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
320                    builder.setMessage(message)
321                    .setCancelable(false)
322                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
323                            public void onClick(DialogInterface dialog, int id) {
324                                    dialog.dismiss();
325                                    StationList.this.finish();
326                            }
327                    })
328                    .show();
329            }
330    
331    
332    
# Line 220  public class StationList extends ListAct Line 336  public class StationList extends ListAct
336                  switch (id) {                  switch (id) {
337                  case DLG_PROGRESS:                  case DLG_PROGRESS:
338                          ProgressDialog dlg = new ProgressDialog(this);                          ProgressDialog dlg = new ProgressDialog(this);
339                          dlg.setMessage("Wait for location fix");                          dlg.setMessage( getString(stationlist_waitforlocation) );
340                          dlg.setCancelable(false);                          dlg.setCancelable(false);
341                          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();  
                                 }  
                         });                      
                         return builder.create();  
342                                                    
343                  default:                  default:
344                          return super.onCreateDialog(id);                                          return super.onCreateDialog(id);                
# Line 276  public class StationList extends ListAct Line 365  public class StationList extends ListAct
365          protected void onListItemClick(ListView l, View v, int position, long id) {          protected void onListItemClick(ListView l, View v, int position, long id) {
366                  super.onListItemClick(l, v, position, id);                  super.onListItemClick(l, v, position, id);
367                                                                    
368                  StationBean station = stations.get(position);                  StationEntry station = stations.entries.get(position);
   
                 double latitude = station.getLatitude();  
                 double longitude = station.getLongitude();  
   
   
369                                    
370                  Intent intent = new Intent(this, DepartureList.class);                  if (isLaunchedforShortcut == true) {
371                  intent.putExtra("name", station.getName());                          Intent i = new Intent();
372                  intent.putExtra("distance", station.getDistance());                          i.putExtra("station", station);
373                  intent.putExtra("latitude", latitude);                          setResult(Activity.RESULT_OK, i);
374                  intent.putExtra("longitude", longitude);                          finish();
375                  intent.putExtra("stationid", station.getId());                  } else {                
376                  intent.putExtra("address", station.getAddress());                          Intent intent = new Intent(this, DepartureList.class);
377                  startActivity(intent);                          intent.putExtra("stationbean", station);
378                            startActivity(intent);
379                    }
380          }          }
381    
382          /////////////////////////////////////////////////////////////          /////////////////////////////////////////////////////////////
383          //          //
384    
385          public void startLookup() {          public void startNearestLookup() {
386                  isRunning = true;                  dialogMessage = getString( stationlist_waitforlocation );
                 dialogMessage = "Wait for location fix";  
387                  showDialog(DLG_PROGRESS);                  showDialog(DLG_PROGRESS);
388                                    
389                  locator.locateStations();                  locationLookup.locateStations();
390                  stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000);                  stationsFetched.sendEmptyMessageDelayed(0, 500);
391          }          }
392                    
393          void startNameSearch(String name) {          void startNameLookup(String name) {
                 dialogMessage = "Finding stations by name";  
                 showDialog(DLG_PROGRESS);  
   
                 findStationsTask = new FindStationsTask();  
                 findStationsTask.searchByName(name, locator.getLocation());  
                 findStationsTask.execute();  
394                                    
395                    stations = stationProvider.lookupStationsByName(name);
396                    getListView().invalidateViews();
397                    adapter.setStations( stations );                                
398          }          }
399                    
400          public void startFavoriteLookup() {          public void startFavoriteLookup() {
401                                    
402                  if (favorites.size() > 0) {                  if (favorites.size() > 0) {
403                          dialogMessage = "Loading favorites";                          
404                          showDialog(DLG_PROGRESS);                          stations = stationProvider.lookupStationsByIds( favorites.toString() );
405                            getListView().invalidateViews();
406                          findStationsTask = new FindStationsTask();                          adapter.setStations( stations );                
407                          findStationsTask.searchByIds(favorites.toString(), locator.getLocation());                          
408                          findStationsTask.execute();                          
409                  } else {                  } else {
410                          MessageBox.showMessage(this, "Favorite list is empty");                          showMessageAndClose( getString( stationlist_nofavorites ) );
411                  }                  }
412          }          }
413    
414    
415                    
416          void startLocatorTask()          void startNearestLookupPhase2()
417          {          {      
418                  dialogMessage = "Finding nearby stations";                  stations = stationProvider.lookupStationsByLocation( locationLookup.getLocation() );
419                  showDialog(DLG_PROGRESS);                  getListView().invalidateViews();
420                                    adapter.setStations( stations );
                 findStationsTask = new FindStationsTask();  
                 findStationsTask.searchByLocation( locator.getLocation() );  
                 findStationsTask.execute();      
421          }          }
           
   
         String lookupAddress(double latitude, double longitude) {  
422                                    
                 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();  
         }  
           
423                    
424          ////////////////////////////////////////////////////////////////////////////          ////////////////////////////////////////////////////////////////////////////
425          // Inner classes          // Inner classes
# Line 376  public class StationList extends ListAct Line 428  public class StationList extends ListAct
428                  @Override                  @Override
429                  public void handleMessage(Message msg) {                  public void handleMessage(Message msg) {
430    
431                          switch (msg.what) {                          LocationLookup.LookupStates state = locationLookup.getState();
432    
433    
434                            switch (state) {
435                          case GOTLOCATION:                          case GOTLOCATION:
436                                  dismissDialog(DLG_PROGRESS);                                  dismissDialog(DLG_PROGRESS);
437                                    
438                                  startLocatorTask();                                  startNearestLookupPhase2();
439                                  location = GeoPair.fromLocation( locator.getLocation() );  
440                                                                    return;
                                 break;  
441    
442                          case NOPROVIDER:                          case NOPROVIDER:
443                                  dismissDialog(DLG_PROGRESS);                                  dismissDialog(DLG_PROGRESS);
444                                  MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps.");                                  MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider), true );
445                                  break;                                  //StationList.this.finish();
446                          case LOCATIONFIXTIMEOUT:                                                                  return;
447                                  if (isRunning) {                          case IDLE:
448                                          locator.stopSearch();                                  Log.e("TrainInfo", "How did this happen ???");
449                                          if (locator.hasLocation()) {                                  dismissDialog(DLG_PROGRESS); // how did we get here ??
450                                                  stationsFetched.sendEmptyMessage( GOTLOCATION );                                  return;
451                                          } 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;  
452                          }                          }
                         isRunning = false;  
                 }  
         };  
453    
           
         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() {  
454    
                         if (method.equals(LookupMethod.MethodNone))  
                                 throw new RuntimeException("Method not set");  
                         super.onPreExecute();  
                 }  
                   
                 @Override  
                 protected Void doInBackground(Void... params) {  
                   
                         if (method.equals(LookupMethod.ByLocation))  
                                 success = stationProvider.lookupStations(loc);  
                           
                         if (method.equals(LookupMethod.ByName))  
                                 success = stationProvider.lookupStationsByName(name);  
                           
                         if (method.equals(LookupMethod.ByList))  
                                 success = stationProvider.lookupStationsByIds(ids);  
                           
                         Location dummy = new Location("gps");  
                         List<StationBean> 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;  
                 }  
455    
456                  @Override                          if (locationLookup.elapsedTime() >=  GPS_TIMEOUT_MS) {
457                  protected void onPostExecute(Void result) {                                  dismissDialog(DLG_PROGRESS);
458                          super.onPostExecute(result);  
459                          dialog.dismiss();  
460                                                            locationLookup.stopSearch();
461                          if (success) {                            
462                                  if (stationProvider.getStations().size() == 0)                                  if (locationLookup.hasLocation()) {
463                                          MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?!                                          startNearestLookupPhase2();
464                                  stations = stationProvider.getStations();                                  } else {                                                
465                                  adapter.setStations( stations );                                                                          AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                
466                                                                            builder.setMessage(  getString( stationlist_gpstimeout) );
467                          } else { //communication or parse errors                                          builder.setCancelable(true);
468                                  AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                                                          builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
469                                  builder.setMessage("Error on finding nearby stations");                                                  public void onClick(DialogInterface dialog, int id) {
470                                  builder.setCancelable(true);                                                          dialog.dismiss();
471                                  builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {                                                          startNearestLookup();
472                                          public void onClick(DialogInterface dialog, int id) {  
473                                                  dialog.dismiss();                                                  }
474                                                                                            });
475                                                  stationsFetched.post( new Runnable() {                                          builder.setNegativeButton( getString(generic_cancel), new DialogInterface.OnClickListener() {
476                                                          @Override                                                  public void onClick(DialogInterface dialog, int id) {
477                                                          public void run() {                                                          dialog.dismiss();
478                                                                  startLocatorTask();                                                                                                                      StationList.this.finish(); // Close this Activity
479                                                          }                                                  }                                                      
480                                                  });                                          });
481                                          }                                          builder.show();
482                                  });  
483                                  builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {                                  }
484                                          public void onClick(DialogInterface dialog, int id) {                          } else {
485                                                  dialog.dismiss();                                  if (locationLookup.hasGps()) {
486                                          }                                                                                                int count = locationLookup.getSatCount();
487                                  });                                                                                                                                      String dialogMessage = getString( stationlist_waitforlocation ) + "\n" + getString( stationlist_satellitecount ) + ": " + count;
488                                  builder.show();                                                                  dialog.setMessage( dialogMessage );
489                                    }
490                                    this.sendEmptyMessageDelayed(0, 500);
491                          }                          }
492                            
493                  }                  }
494          }          }
495            
496    
497    
498                    
499          class FavoritesMenu implements OnCreateContextMenuListener {          class FavoritesMenu implements OnCreateContextMenuListener {
500                  private final static int FAVORITES_ADD = 9001;                  private final static int FAVORITES_ADD = 9001;
# Line 537  public class StationList extends ListAct Line 508  public class StationList extends ListAct
508                                                                                                    
509                          AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;                          AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
510                          selectedPosition = info.position;                          selectedPosition = info.position;
511                          int stationID = stations.get(selectedPosition).getId();                          int stationID = stations.entries.get(selectedPosition).getId();
512    
513                          if (!favorites.contains(stationID)) {                          if (!favorites.contains(stationID)) {
514                                  menu.add(0, FAVORITES_ADD, 0, "Add to favorites");                                  menu.add(0, FAVORITES_ADD, 0, getString(stationlist_addfavorite) );
515                          } else {                          } else {
516                                  menu.add(0, FAVORITES_REMOVE, 0, "Remove from favorites");                                  menu.add(0, FAVORITES_REMOVE, 0, getString(stationlist_removefavorite) );
517                          }                          }
518                                                    
519                  }                  }
520                                    
521                  public void onContextItemSelected(MenuItem item) {                  public void onContextItemSelected(MenuItem item) {
522                          StationBean sb = stations.get(selectedPosition);                          StationEntry sb = stations.entries.get(selectedPosition);
523                                                    
524                          int stationID = sb.getId();                          int stationID = sb.getId();
525                          if (item.getItemId() == FAVORITES_ADD) {                          if (item.getItemId() == FAVORITES_ADD) {
526                                  favorites.add(stationID);                                  favorites.add(stationID);
527                                  Toast.makeText(StationList.this, "Station added", Toast.LENGTH_SHORT).show();                                  Toast.makeText(StationList.this, getString(stationlist_stationadded), Toast.LENGTH_SHORT).show();
528                          } else {                          } else {
529                                    
530                                  favorites.remove(stationID);                                  favorites.remove(stationID);
531                                  Toast.makeText(StationList.this, "Station removed", Toast.LENGTH_SHORT).show();                                  Toast.makeText(StationList.this, getString(stationlist_stationremoved), Toast.LENGTH_SHORT).show();
532                                    
533                                    
534                                    if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) {
535                                            stations.entries.remove(selectedPosition);
536                                            adapter.notifyDataSetChanged();
537                                    }
538                          }                          }
539                          Editor ed = prefs.edit();                          Editor ed = prefs.edit();
540                          ed.putString("favorites", favorites.toString());                          ed.putString("favorites", favorites.toString());

Legend:
Removed from v.441  
changed lines
  Added in v.1576

  ViewVC Help
Powered by ViewVC 1.1.20