/[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 433 by torben, Sat Oct 10 11:30:08 2009 UTC revision 948 by torben, Fri Jul 2 14:58:44 2010 UTC
# Line 2  package dk.thoerup.traininfo; Line 2  package dk.thoerup.traininfo;
2    
3  import java.util.ArrayList;  import java.util.ArrayList;
4  import java.util.List;  import java.util.List;
 import java.util.Locale;  
 import java.util.prefs.Preferences;  
5    
6    
7    import android.app.Activity;
8  import android.app.AlertDialog;  import android.app.AlertDialog;
9  import android.app.Dialog;  import android.app.Dialog;
10  import android.app.ListActivity;  import android.app.ListActivity;
# Line 12  import android.app.ProgressDialog; Line 12  import android.app.ProgressDialog;
12  import android.content.DialogInterface;  import android.content.DialogInterface;
13  import android.content.Intent;  import android.content.Intent;
14  import android.content.SharedPreferences;  import android.content.SharedPreferences;
15  import android.location.Address;  import android.content.SharedPreferences.Editor;
 import android.location.Geocoder;  
16  import android.location.Location;  import android.location.Location;
17  import android.os.AsyncTask;  import android.os.AsyncTask;
18  import android.os.Bundle;  import android.os.Bundle;
19  import android.os.Handler;  import android.os.Handler;
20  import android.os.Message;  import android.os.Message;
21    
22  import android.util.Log;  import android.util.Log;
23  import android.view.ContextMenu;  import android.view.ContextMenu;
24  import android.view.LayoutInflater;  import android.view.LayoutInflater;
# Line 38  import dk.thoerup.traininfo.stationmap.S Line 38  import dk.thoerup.traininfo.stationmap.S
38  import dk.thoerup.traininfo.util.IntSet;  import dk.thoerup.traininfo.util.IntSet;
39  import dk.thoerup.traininfo.util.MessageBox;  import dk.thoerup.traininfo.util.MessageBox;
40    
41    import static dk.thoerup.traininfo.R.string.*;
42    
43  public class StationList extends ListActivity  {  public class StationList extends ListActivity  {
44          public static final int GOTLOCATION = 1001;          public static final int GOTLOCATION = 1001;
45          public static final int GOTSTATIONLIST = 1002;          public static final int GOTSTATIONLIST = 1002;
46          public static final int NOPROVIDER = 1003;          public static final int NOPROVIDER = 1003;
47          public static final int LOCATIONFIXTIMEOUT = 1004;          public static final int LOCATIONFIXTIMEOUT = 1004;
48                    
         public static final int OPTIONS_RESCAN = 2001;  
         public static final int OPTIONS_NAMESEARCH = 2002;  
49          public static final int OPTIONS_MAP = 2003;          public static final int OPTIONS_MAP = 2003;
50          public static final int OPTIONS_ABOUT = 2004;          public static final int OPTIONS_GPSINFO = 2004;
         public static final int OPTIONS_FAVORITES = 2005;  
           
   
51                    
52          public static final int DLG_PROGRESS = 3001;          public static final int DLG_PROGRESS = 3001;
53          public static final int DLG_STATIONNAME = 3002;          public static final int DLG_STATIONNAME = 3002;
54                    
55          /** Called when the activity is first created. */          
56            public static final int GPS_TIMEOUT_MS = 17500; //how long are we willing to wait for gps fix -in milliseconds
57            
58            
59            static enum LookupMethod {
60                    ByLocation,
61                    ByName,
62                    ByList,
63                    MethodNone
64            }
65            
66            
67          String dialogMessage = "";          String dialogMessage = "";
68          ProgressDialog dialog;          ProgressDialog dialog;
69          LocationLookup locator = null;          LocationLookup locationLookup = null;
70          LocatorTask locatorTask;          FindStationsTask findStationsTask;
71          StationsFetchedHandler stationsFetched = new StationsFetchedHandler();          StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
72                    
73          GeoPair location = new GeoPair();          GeoPair location = new GeoPair();
74            
75            boolean isLaunchedforShortcut;
76          boolean isRunning = false;          boolean isRunning = false;
77          List<StationBean> stations = new ArrayList<StationBean>();          List<StationBean> stations = new ArrayList<StationBean>();
78                    
# Line 73  public class StationList extends ListAct Line 82  public class StationList extends ListAct
82                    
83          FavoritesMenu contextMenu = new FavoritesMenu();          FavoritesMenu contextMenu = new FavoritesMenu();
84          IntSet favorites = new IntSet();          IntSet favorites = new IntSet();
85            
86          static enum LookupMethod {          WelcomeScreen.ListType listType;
                 ByLocation,  
                 ByName,  
                 ByList,  
                 MethodNone  
         }  
           
87          SharedPreferences prefs;          SharedPreferences prefs;
88                    
89          ///////////////////////////////////////////////////////////////////////////////////////////          ///////////////////////////////////////////////////////////////////////////////////////////
# Line 90  public class StationList extends ListAct Line 93  public class StationList extends ListAct
93          @Override          @Override
94          public void onCreate(Bundle savedInstanceState) {          public void onCreate(Bundle savedInstanceState) {
95                  super.onCreate(savedInstanceState);                  super.onCreate(savedInstanceState);
96                  setContentView(R.layout.main);                  setContentView(R.layout.stationlist);
97                                    
98                                    
99                  adapter = new StationListAdapter(this);                  adapter = new StationListAdapter(this);
# Line 99  public class StationList extends ListAct Line 102  public class StationList extends ListAct
102                  ListView lv = getListView();                  ListView lv = getListView();
103                  lv.setOnCreateContextMenuListener(contextMenu);                  lv.setOnCreateContextMenuListener(contextMenu);
104                                    
105                  locator = new LocationLookup(this, stationsFetched);                  locationLookup = new LocationLookup(this, stationsFetched);
106                                    
107    
108                  prefs = getSharedPreferences("TrainStation", 0);                  prefs = getSharedPreferences("TrainStation", 0);
# Line 108  public class StationList extends ListAct Line 111  public class StationList extends ListAct
111                          favorites.fromString(favoriteString);                          favorites.fromString(favoriteString);
112                  }                  }
113                                    
114                    listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type");
115                    setTitle();
116                    
117                    isLaunchedforShortcut = getIntent().getBooleanExtra("shortcut", false);
118                    
119                  if (savedInstanceState == null) {                  if (savedInstanceState == null) {
120                          startLookup();  
121                            
122                            switch (listType) {
123                            case ListNearest:
124                                    startLookup();
125                                    break;
126                            case ListSearch:
127                                    this.showDialogSafe(DLG_STATIONNAME);
128                                    break;
129                            case ListFavorites:
130                                    startFavoriteLookup();
131                                    break;
132                            default:
133                                    // Not possible !?!
134                            }
135                            
136                  } else {                  } else {
137                          stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");                          stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");
138                          adapter.setStations(stations);                          adapter.setStations(stations);
139                          location = (GeoPair) savedInstanceState.getSerializable("location");                          location = (GeoPair) savedInstanceState.getSerializable("location");
140                  }                  }
141                    
142          }          }
143            
144    
145            @Override
146            protected void onDestroy() {
147                    super.onDestroy();
148                    
149                    if (findStationsTask != null) {
150                            findStationsTask.cancel(true);
151                    }
152                    if (locationLookup != null) {
153                            locationLookup.stopSearch();
154                    }
155                    isRunning = false;
156            }
157    
158            
159            protected void setTitle() {
160                    String dialogTitle = getResources().getString(app_name);
161                    switch (listType) {
162                    case ListNearest:
163                            dialogTitle += " - " + getString(stationlist_nearbystations);
164                            break;
165                    case ListSearch:
166                            dialogTitle += " - " + getString(stationlist_search);
167                            break;
168                    case ListFavorites:
169                            dialogTitle += " - " + getString(stationlist_favorites);
170                            break;
171                    default:
172                            dialogTitle = "";//not possible                                
173                    }
174            
175                    setTitle(dialogTitle);
176                    
177            }
178            
179            
180            /* these 3 dialogs helper functions are very rude and ugly hack
181             * to remove these auto-reported exceptions
182             * - android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@436aaef8 is not valid; is your activity running?
183             * - java.lang.IllegalArgumentException: View not attached to window manager
184             */
185            
186            public void showDialogSafe(int id) {
187                    try {
188                            showDialog(id);
189                    } catch (Exception e) {
190                            Log.e("StationList", "showDialog failed", e);
191                    }
192            }
193            
194            public void dismissDialogSafe(int id) {
195                    try {
196                            dismissDialog(id);
197                    } catch (Exception e) {
198                            Log.e("StationList", "dismissDialog failed", e);
199                    }
200            }
201            public void dismissDialogSafe(Dialog dlg) {
202                    try {
203                            dlg.dismiss();
204                    } catch (Exception e) {
205                            Log.e("StationList", "dismissDialog failed", e);
206                    }
207            }
208            
209            public void builderShowSafe(AlertDialog.Builder builder) {
210                    try {
211                            builder.show();
212                    } catch (Exception e) {
213                            Log.e("StationList", "builder.show() failed", e);
214                    }
215                    
216            }
217            /* EOF rude and ugly dialog hack */
218            
219    
220    
221      @Override      @Override
# Line 125  public class StationList extends ListAct Line 225  public class StationList extends ListAct
225                  dialog.dismiss();                  dialog.dismiss();
226          outState.putSerializable("stations", (ArrayList<StationBean>) stations);          outState.putSerializable("stations", (ArrayList<StationBean>) stations);
227          outState.putSerializable("location", location);          outState.putSerializable("location", location);
228            
229      }      }
230                    
231                    
# Line 133  public class StationList extends ListAct Line 234  public class StationList extends ListAct
234          public boolean onCreateOptionsMenu(Menu menu) {          public boolean onCreateOptionsMenu(Menu menu) {
235                  MenuItem item;                  MenuItem item;
236                                    
237                  item = menu.add(0, OPTIONS_RESCAN, 0, "Find 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, "Show station map");  
238                  item.setIcon(android.R.drawable.ic_menu_mapmode);                  item.setIcon(android.R.drawable.ic_menu_mapmode);
239                                    
240                  item = menu.add(0, OPTIONS_ABOUT, 0, "About");                  item = menu.add(0, OPTIONS_GPSINFO, 0, getString(stationlist_gpsinfo));
241                  item.setIcon(android.R.drawable.ic_menu_info_details);                  item.setIcon(android.R.drawable.ic_menu_mapmode);              
242                    
243                  return true;                  return true;
244          }          }
245    
# Line 154  public class StationList extends ListAct Line 247  public class StationList extends ListAct
247          public boolean onOptionsItemSelected(MenuItem item) {          public boolean onOptionsItemSelected(MenuItem item) {
248                  boolean retval = true;                  boolean retval = true;
249    
250                                    //TODO: Cleanup
251                  switch (item.getItemId()) {                  switch (item.getItemId()) {
                 case OPTIONS_RESCAN:  
                         startLookup();  
                         break;  
                 case OPTIONS_NAMESEARCH:  
                         showDialog(DLG_STATIONNAME);  
                         break;  
                 case OPTIONS_FAVORITES:  
                         startFavoriteLookup();  
                         break;  
252                  case OPTIONS_MAP:                  case OPTIONS_MAP:
253                                                    
254                          Intent intent = new Intent(this,StationMapView.class);                          Intent intent = new Intent(this,StationMapView.class);
                         intent.putExtra("userlocation", location );  
255                                                    
256                          ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();                          ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
257                          for (StationBean st : stations ) {                          for (StationBean st : stations ) {
# Line 179  public class StationList extends ListAct Line 262  public class StationList extends ListAct
262                                                    
263                          startActivity(intent);                          startActivity(intent);
264                          break;                          break;
265                  case OPTIONS_ABOUT:                  case OPTIONS_GPSINFO:
266                          String ver = this.getResources().getString(R.string.app_version);                          Location loc = locationLookup.getLocation();
                           
                         Location loc = locator.getLocation();  
267                          StringBuffer message = new StringBuffer();                          StringBuffer message = new StringBuffer();
268                          message.append("TrainInfo DK v").append(ver).append("\n");                          message.append( getString(stationlist_locationinfo) ).append(":\n");
269                          message.append("By Torben Nielsen\n");                          if (loc != null) {
270                          message.append("\n");                                  message.append( getString(stationlist_obtainedby) ).append( loc.getProvider() ).append("\n");
271                          message.append("Location info:\n");                                  message.append( getString(stationlist_accuracy) ).append( (int)loc.getAccuracy()).append("m\n");
272                          message.append("-Obtained by: ").append(loc != null ? loc.getProvider() : "-").append("\n");                                  message.append( getString(stationlist_latitude) ).append( (float)loc.getLatitude()).append("\n");
273                          message.append("-Accuracy: ").append(loc != null ? (int)loc.getAccuracy() : "-").append("m\n");                                  message.append( getString(stationlist_longitude) ).append( (float)loc.getLongitude() ).append("\n");
274                            } else {
275                          MessageBox.showMessage(this, message.toString());                                  message.append( getString(stationlist_nolocation) );
276                            }                      
277                            
278                            MessageBox.showMessage(this, message.toString(), false);
279                          break;                          break;
280                  default:                  default:
281                          retval = super.onOptionsItemSelected(item);                          retval = super.onOptionsItemSelected(item);
# Line 209  public class StationList extends ListAct Line 293  public class StationList extends ListAct
293    
294    
295          }          }
296            
297            public void showMessageAndClose(String message) {
298                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
299                    builder.setMessage(message)
300                    .setCancelable(false)
301                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
302                            public void onClick(DialogInterface dialog, int id) {
303                                    dialog.dismiss();
304                                    StationList.this.finish();
305                            }
306                    })
307                    .show();
308            }
309    
310    
311    
# Line 218  public class StationList extends ListAct Line 315  public class StationList extends ListAct
315                  switch (id) {                  switch (id) {
316                  case DLG_PROGRESS:                  case DLG_PROGRESS:
317                          ProgressDialog dlg = new ProgressDialog(this);                          ProgressDialog dlg = new ProgressDialog(this);
318                          dlg.setMessage("Wait for location fix");                          dlg.setMessage( getString(stationlist_waitforlocation) );
319                          dlg.setCancelable(false);                          dlg.setCancelable(false);
320                          return dlg;                                              return dlg;                    
321                  case DLG_STATIONNAME:                  case DLG_STATIONNAME:
# Line 228  public class StationList extends ListAct Line 325  public class StationList extends ListAct
325                                                    
326                          AlertDialog.Builder builder = new AlertDialog.Builder(this);                          AlertDialog.Builder builder = new AlertDialog.Builder(this);
327                                                    
328                          builder.setTitle("Station search");                          builder.setTitle( getString(stationlist_stationsearch) );
329                          builder.setView(rootView);                          builder.setView(rootView);
330                          builder.setCancelable(true);                          builder.setCancelable(true);
331                          builder.setPositiveButton("Search", new DialogInterface.OnClickListener() {                          builder.setPositiveButton( getString(generic_search), new DialogInterface.OnClickListener() {
332                                  public void onClick(DialogInterface dialog, int which) {                                  public void onClick(DialogInterface dialog, int which) {
333                                          EditText et = (EditText) rootView.findViewById(R.id.EditText);                                          EditText et = (EditText) rootView.findViewById(R.id.EditText);
334                                          dialog.dismiss();                                          dialog.dismiss();
335                                          if (et.getText().toString().length() >= 2) {                                          String search = et.getText().toString().trim();
336                                                  startNameSearch(et.getText().toString());                                          if (search.length() >= 2) {
337                                                    startNameSearch(search);
338                                          } else {                                          } else {
339                                                  MessageBox.showMessage(StationList.this, "Two characters minimum" );                                                  showMessageAndClose( getString(stationlist_twocharmin) );
340                                          }                                          }
341                                  }                                  }
342                          });                          });
343                          builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {                          builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
344                                  public void onClick(DialogInterface dialog, int which) {                                  public void onClick(DialogInterface dialog, int which) {
345                                          dialog.dismiss();                                          dialog.dismiss();
346                                            StationList.this.finish(); // Close this Activity
347                                  }                                  }
348                          });                                              });                    
349                          return builder.create();                          return builder.create();
# Line 275  public class StationList extends ListAct Line 374  public class StationList extends ListAct
374                  super.onListItemClick(l, v, position, id);                  super.onListItemClick(l, v, position, id);
375                                                                    
376                  StationBean station = stations.get(position);                  StationBean station = stations.get(position);
   
                 double latitude = station.getLatitude();  
                 double longitude = station.getLongitude();  
   
   
377                                    
378                  Intent intent = new Intent(this, DepartureList.class);                  if (isLaunchedforShortcut == true) {
379                  intent.putExtra("name", station.getName());                          Intent i = new Intent();
380                  intent.putExtra("distance", station.getDistance());                          i.putExtra("station", station);
381                  intent.putExtra("latitude", latitude);                          setResult(Activity.RESULT_OK, i);
382                  intent.putExtra("longitude", longitude);                          finish();
383                  intent.putExtra("stationid", station.getId());                  } else {                
384                  intent.putExtra("address", station.getAddress());                          Intent intent = new Intent(this, DepartureList.class);
385                  startActivity(intent);                          intent.putExtra("stationbean", station);
386                            startActivity(intent);
387                    }
388          }          }
389    
390          /////////////////////////////////////////////////////////////          /////////////////////////////////////////////////////////////
391          //          //
392    
393          public void startLookup() {          public void startLookup() {
394                  isRunning = true;                  isRunning = true;              
395                  dialogMessage = "Wait for location fix";                  dialogMessage = getString( stationlist_waitforlocation );
396                  showDialog(DLG_PROGRESS);                  showDialogSafe(DLG_PROGRESS);
397                                    
398                  locator.locateStations();                  locationLookup.locateStations();
399                  stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000);                  stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, GPS_TIMEOUT_MS);
400          }          }
401                    
402          void startNameSearch(String name) {          void startNameSearch(String name) {
403                  dialogMessage = "Finding stations by name";                  dialogMessage = getString( stationlist_findbyname );
404                  showDialog(DLG_PROGRESS);                  showDialogSafe(DLG_PROGRESS);
405    
406                  locatorTask = new LocatorTask();                  findStationsTask = new FindStationsTask();
407                  locatorTask.searchByName(name, locator.getLocation());                  findStationsTask.searchByName(name);
408                  locatorTask.execute();                  findStationsTask.execute();
409                                    
410          }          }
411                    
412          public void startFavoriteLookup() {          public void startFavoriteLookup() {
413                                    
414                  if (favorites.toString().length() > 0) {                  if (favorites.size() > 0) {
415                          dialogMessage = "Loading favorites";                          dialogMessage = getString( stationlist_loadfavorites );
416                          showDialog(DLG_PROGRESS);                          showDialogSafe(DLG_PROGRESS);
417    
418                          locatorTask = new LocatorTask();                          findStationsTask = new FindStationsTask();
419                          locatorTask.searchByIds(favorites.toString(), locator.getLocation());                          findStationsTask.searchByIds( favorites.toString() );
420                          locatorTask.execute();                          findStationsTask.execute();
421                  } else {                  } else {
422                          MessageBox.showMessage(this, "Favorite list is empty");                          showMessageAndClose( getString( stationlist_nofavorites ) );
423                  }                  }
424          }          }
425    
# Line 331  public class StationList extends ListAct Line 427  public class StationList extends ListAct
427                    
428          void startLocatorTask()          void startLocatorTask()
429          {          {
430                  dialogMessage = "Finding nearby stations";                  dialogMessage = getString( stationlist_findingnearby );
431                  showDialog(DLG_PROGRESS);                  showDialogSafe(DLG_PROGRESS);
432                                    
433                  locatorTask = new LocatorTask();                  findStationsTask = new FindStationsTask();
434                  locatorTask.searchByLocation( locator.getLocation() );                  findStationsTask.searchByLocation( locationLookup.getLocation() );
435                  locatorTask.execute();                    findStationsTask.execute();    
436          }          }
           
   
         String lookupAddress(double latitude, double longitude) {  
437                                    
                 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();  
         }  
           
438                    
439          ////////////////////////////////////////////////////////////////////////////          ////////////////////////////////////////////////////////////////////////////
440          // Inner classes          // Inner classes
# Line 376  public class StationList extends ListAct Line 445  public class StationList extends ListAct
445    
446                          switch (msg.what) {                          switch (msg.what) {
447                          case GOTLOCATION:                          case GOTLOCATION:
448                                  dismissDialog(DLG_PROGRESS);                                  dismissDialogSafe(DLG_PROGRESS);
449                                                                    
450                                  startLocatorTask();                                  startLocatorTask();
451                                  location = GeoPair.fromLocation( locator.getLocation() );                                  location = GeoPair.fromLocation( locationLookup.getLocation() );
452                                                                    
453                                  break;                                  break;
454    
455                          case NOPROVIDER:                          case NOPROVIDER:
456                                  dismissDialog(DLG_PROGRESS);                                  dismissDialogSafe(DLG_PROGRESS);
457                                  MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps.");                                  MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider), true );
458                                    //StationList.this.finish();
459                                  break;                                  break;
460                          case LOCATIONFIXTIMEOUT:                                                          case LOCATIONFIXTIMEOUT:                                
461                                  if (isRunning) {                                  if (isRunning) {
462                                          locator.stopSearch();                                          locationLookup.stopSearch();
463                                          if (locator.hasLocation()) {                                          if (locationLookup.hasLocation()) {
464                                                  stationsFetched.sendEmptyMessage( GOTLOCATION );                                                  stationsFetched.sendEmptyMessage( GOTLOCATION );
465                                          } else {                                                                                          } else {                                                
466                                                  dismissDialog(DLG_PROGRESS);                                                  dismissDialogSafe(DLG_PROGRESS);
467                                                                                                    
468                                                  AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                                                                  AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                
469                                                  builder.setMessage("Location fix timed out");                                                  builder.setMessage(  getString( stationlist_gpstimeout) );
470                                                  builder.setCancelable(true);                                                  builder.setCancelable(true);
471                                                  builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {                                                  builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
472                                                          public void onClick(DialogInterface dialog, int id) {                                                          public void onClick(DialogInterface dialog, int id) {
473                                                                  dialog.dismiss();                                                                  dialog.dismiss();
474                                                                  startLookup();                                                                  startLookup();
475                                                                                                                                    
476                                                          }                                                          }
477                                                  });                                                  });
478                                                  builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {                                                  builder.setNegativeButton( getString(generic_cancel), new DialogInterface.OnClickListener() {
479                                                          public void onClick(DialogInterface dialog, int id) {                                                          public void onClick(DialogInterface dialog, int id) {
480                                                                  dialog.dismiss();                                                                  dialog.dismiss();
481                                                          }                                                                                                                }                                                      
482                                                  });                                                                                                                                              });
483                                                  builder.show();                                                  builderShowSafe(builder); // builder.show()
484    
485                                          }                                          }
486                                  }                                  }
# Line 421  public class StationList extends ListAct Line 491  public class StationList extends ListAct
491          };          };
492    
493                    
494          class LocatorTask extends AsyncTask<Void,Void,Void> {          class FindStationsTask extends AsyncTask<Void,Void,Void> {
495                                    
496                  LookupMethod method = LookupMethod.MethodNone;                  LookupMethod method = LookupMethod.MethodNone;
497                  boolean success;                  boolean success;
# Line 429  public class StationList extends ListAct Line 499  public class StationList extends ListAct
499                  Location loc;                  Location loc;
500                  String ids;                  String ids;
501                                    
502                  public void searchByName(String n, Location l) {                  public void searchByName(String n) {
503                                                    
504                          method = LookupMethod.ByName;                          method = LookupMethod.ByName;
                         loc = l;  
505                          name = n;                          name = n;
506                  }                  }
507                                    
# Line 441  public class StationList extends ListAct Line 510  public class StationList extends ListAct
510                          loc = l;                          loc = l;
511                  }                  }
512                                    
513                  public void searchByIds(String id, Location l) {                  public void searchByIds(String id) {
514                                                    
515                          method = LookupMethod.ByList;                          method = LookupMethod.ByList;
                         loc = l;  
516                          ids = id;                          ids = id;
517                  }                  }
518                                    
# Line 458  public class StationList extends ListAct Line 526  public class StationList extends ListAct
526                                    
527                  @Override                  @Override
528                  protected Void doInBackground(Void... params) {                  protected Void doInBackground(Void... params) {
529                    
530                          if (method.equals(LookupMethod.ByLocation))                          switch (method) {
531                            case ByLocation:
532                                  success = stationProvider.lookupStations(loc);                                  success = stationProvider.lookupStations(loc);
533                                                            break;
534                          if (method.equals(LookupMethod.ByName))                          case ByName:
535                                  success = stationProvider.lookupStationsByName(name);                                  success = stationProvider.lookupStationsByName(name);
536                                                            break;
537                          if (method.equals(LookupMethod.ByList))                          case ByList:
538                                  success = stationProvider.lookupStationsByIds(ids);                                  success = stationProvider.lookupStationsByIds(ids);
539                                    break;
540                            default:
541                                    success = false; // not possible        
542                            }
543                                                    
                         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) );  
                                 }  
                         }                                                
544                                                    
545                          return null;                          return null;
546                  }                  }
# Line 488  public class StationList extends ListAct Line 548  public class StationList extends ListAct
548                  @Override                  @Override
549                  protected void onPostExecute(Void result) {                  protected void onPostExecute(Void result) {
550                          super.onPostExecute(result);                          super.onPostExecute(result);
551                          dialog.dismiss();                          dismissDialogSafe(dialog);
552                            
553                                                    
554                          if (success) {                                                    if (success) {                          
555                                  if (stationProvider.getStations().size() == 0)                                  if (stationProvider.getStations().size() == 0) {
556                                          MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?!                                          showMessageAndClose(getString(stationlist_nostations));
557                                    }
558                                  stations = stationProvider.getStations();                                  stations = stationProvider.getStations();
559    
560                                    StationList.this.getListView().invalidateViews();
561                                  adapter.setStations( stations );                                                                  adapter.setStations( stations );                                
562                                                                    
563                                    
564                          } else { //communication or parse errors                          } else { //communication or parse errors
565                                  AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                                                  AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                
566                                  builder.setMessage("Error on finding nearby stations");                                  builder.setMessage(getString(stationlist_fetcherror));                          
567                                  builder.setCancelable(true);                                  builder.setCancelable(true);
568                                  builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {                                  builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
569                                          public void onClick(DialogInterface dialog, int id) {                                          public void onClick(DialogInterface dialog, int id) {
570                                                  dialog.dismiss();                                                  dialog.dismiss();
571                                                                                                    
572                                                  stationsFetched.post( new Runnable() {                                                  Runnable runner = null;
573                                                          @Override                                                  switch (method) {
574                                                          public void run() {                                                  case ByLocation:
575                                                                  startLocatorTask();                                                                                                                      runner = new Runnable() {
576                                                          }                                                                  @Override
577                                                  });                                                                  public void run() {
578                                                                            startLocatorTask();                                                            
579                                                                    }
580                                                            };
581                                                            break;
582                                                    case ByName:
583                                                            runner = new Runnable() {
584                                                                    @Override
585                                                                    public void run() {
586                                                                            startNameSearch( FindStationsTask.this.name );
587                                                                    }
588                                                            };
589                                                            break;
590                                                    case ByList:
591                                                            runner = new Runnable() {
592                                                                    @Override
593                                                                    public void run() {
594                                                                            startFavoriteLookup();
595                                                                    }
596                                                            };
597                                                            break;
598                                                    }
599                                                    
600                                                    stationsFetched.post( runner );
601                                          }                                          }
602                                  });                                  });
603                                  builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {                                  builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
604                                          public void onClick(DialogInterface dialog, int id) {                                          public void onClick(DialogInterface dialog, int id) {
605                                                  dialog.dismiss();                                                  dialog.dismiss();
606                                                    StationList.this.finish();
607                                          }                                                                                                }                                                      
608                                  });                                                                                                                              });
609                                  builder.show();                                                          
610                                    builderShowSafe(builder); // builder.show()
611                          }                          }
612                  }                  }
613          }          }
# Line 537  public class StationList extends ListAct Line 627  public class StationList extends ListAct
627                          selectedPosition = info.position;                          selectedPosition = info.position;
628                          int stationID = stations.get(selectedPosition).getId();                          int stationID = stations.get(selectedPosition).getId();
629    
630                          if (!favorites.hasInt(stationID)) {                          if (!favorites.contains(stationID)) {
631                                  menu.add(0, FAVORITES_ADD, 0, "Add to favorites");                                  menu.add(0, FAVORITES_ADD, 0, getString(stationlist_addfavorite) );
632                          } else {                          } else {
633                                  menu.add(0, FAVORITES_REMOVE, 0, "Remove from favorites");                                  menu.add(0, FAVORITES_REMOVE, 0, getString(stationlist_removefavorite) );
634                          }                          }
635                                                    
636                  }                  }
# Line 551  public class StationList extends ListAct Line 641  public class StationList extends ListAct
641                          int stationID = sb.getId();                          int stationID = sb.getId();
642                          if (item.getItemId() == FAVORITES_ADD) {                          if (item.getItemId() == FAVORITES_ADD) {
643                                  favorites.add(stationID);                                  favorites.add(stationID);
644                                  Toast.makeText(StationList.this, "Station added", Toast.LENGTH_SHORT).show();                                  Toast.makeText(StationList.this, getString(stationlist_stationadded), Toast.LENGTH_SHORT).show();
645                          } else {                          } else {
646                                    
647                                  favorites.remove(stationID);                                  favorites.remove(stationID);
648                                  Toast.makeText(StationList.this, "Station removed", Toast.LENGTH_SHORT).show();                                  Toast.makeText(StationList.this, getString(stationlist_stationremoved), Toast.LENGTH_SHORT).show();
649                                    
650                                    
651                                    if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) {
652                                            stations.remove(selectedPosition);
653                                            adapter.notifyDataSetChanged();
654                                    }
655                          }                          }
656                                                    Editor ed = prefs.edit();
657                          prefs.edit().putString("favorites", favorites.toString());                          ed.putString("favorites", favorites.toString());
658                            ed.commit();
659                  }                  }
660          }          }
661  }  }

Legend:
Removed from v.433  
changed lines
  Added in v.948

  ViewVC Help
Powered by ViewVC 1.1.20