/[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 439 by torben, Sun Oct 11 07:07:29 2009 UTC revision 1142 by torben, Tue Sep 28 14:58:45 2010 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.generic_search;
7    import static dk.thoerup.traininfo.R.string.stationlist_accuracy;
8    import static dk.thoerup.traininfo.R.string.stationlist_addfavorite;
9    import static dk.thoerup.traininfo.R.string.stationlist_favorites;
10    import static dk.thoerup.traininfo.R.string.stationlist_fetcherror;
11    import static dk.thoerup.traininfo.R.string.stationlist_findbyname;
12    import static dk.thoerup.traininfo.R.string.stationlist_findingnearby;
13    import static dk.thoerup.traininfo.R.string.stationlist_gpsinfo;
14    import static dk.thoerup.traininfo.R.string.stationlist_gpstimeout;
15    import static dk.thoerup.traininfo.R.string.stationlist_latitude;
16    import static dk.thoerup.traininfo.R.string.stationlist_loadfavorites;
17    import static dk.thoerup.traininfo.R.string.stationlist_locationinfo;
18    import static dk.thoerup.traininfo.R.string.stationlist_longitude;
19    import static dk.thoerup.traininfo.R.string.stationlist_nearbystations;
20    import static dk.thoerup.traininfo.R.string.stationlist_nofavorites;
21    import static dk.thoerup.traininfo.R.string.stationlist_nolocation;
22    import static dk.thoerup.traininfo.R.string.stationlist_nolocationprovider;
23    import static dk.thoerup.traininfo.R.string.stationlist_nostations;
24    import static dk.thoerup.traininfo.R.string.stationlist_obtainedby;
25    import static dk.thoerup.traininfo.R.string.stationlist_removefavorite;
26    import static dk.thoerup.traininfo.R.string.stationlist_search;
27    import static dk.thoerup.traininfo.R.string.stationlist_stationadded;
28    import static dk.thoerup.traininfo.R.string.stationlist_stationmap;
29    import static dk.thoerup.traininfo.R.string.stationlist_stationremoved;
30    import static dk.thoerup.traininfo.R.string.stationlist_stationsearch;
31    import static dk.thoerup.traininfo.R.string.stationlist_twocharmin;
32    import static dk.thoerup.traininfo.R.string.stationlist_waitforlocation;
33    import static dk.thoerup.traininfo.R.string.stationlist_satellitecount;
34    
35  import java.util.ArrayList;  import java.util.ArrayList;
 import java.util.List;  
 import java.util.Locale;  
36    
37    import android.app.Activity;
38  import android.app.AlertDialog;  import android.app.AlertDialog;
39  import android.app.Dialog;  import android.app.Dialog;
40  import android.app.ListActivity;  import android.app.ListActivity;
# Line 12  import android.content.DialogInterface; Line 43  import android.content.DialogInterface;
43  import android.content.Intent;  import android.content.Intent;
44  import android.content.SharedPreferences;  import android.content.SharedPreferences;
45  import android.content.SharedPreferences.Editor;  import android.content.SharedPreferences.Editor;
 import android.location.Address;  
 import android.location.Geocoder;  
46  import android.location.Location;  import android.location.Location;
47  import android.os.AsyncTask;  import android.os.AsyncTask;
48  import android.os.Bundle;  import android.os.Bundle;
# Line 31  import android.widget.AdapterView; Line 60  import android.widget.AdapterView;
60  import android.widget.EditText;  import android.widget.EditText;
61  import android.widget.ListView;  import android.widget.ListView;
62  import android.widget.Toast;  import android.widget.Toast;
63    import dk.thoerup.android.traininfo.common.StationBean;
64    import dk.thoerup.android.traininfo.common.StationBean.StationEntry;
65  import dk.thoerup.traininfo.provider.ProviderFactory;  import dk.thoerup.traininfo.provider.ProviderFactory;
66  import dk.thoerup.traininfo.provider.StationProvider;  import dk.thoerup.traininfo.provider.StationProvider;
67  import dk.thoerup.traininfo.stationmap.GeoPair;  import dk.thoerup.traininfo.stationmap.GeoPair;
# Line 39  import dk.thoerup.traininfo.util.IntSet; Line 70  import dk.thoerup.traininfo.util.IntSet;
70  import dk.thoerup.traininfo.util.MessageBox;  import dk.thoerup.traininfo.util.MessageBox;
71    
72  public class StationList extends ListActivity  {  public class StationList extends ListActivity  {
73          public static final int GOTLOCATION = 1001;          public enum LookupStates {
74          public static final int GOTSTATIONLIST = 1002;                  GOTLOCATION,
75          public static final int NOPROVIDER = 1003;                  GOTSTATIONLIST,
76          public static final int LOCATIONFIXTIMEOUT = 1004;                  NOPROVIDER,
77                    LOCATIONFIXTIMEOUT,
78                    GPS_SAT_COUNT
79            }
80                    
         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;  
81                    
82            public static final int OPTIONS_MAP = 2003;
83            public static final int OPTIONS_GPSINFO = 2004;
84                    
85          public static final int DLG_PROGRESS = 3001;          public static final int DLG_PROGRESS = 3001;
86          public static final int DLG_STATIONNAME = 3002;          public static final int DLG_STATIONNAME = 3002;
87                    
88          /** Called when the activity is first created. */          
89            public static final int GPS_TIMEOUT_MS = 15000; //how long are we willing to wait for gps fix -in milliseconds
90            
91            
92            static enum LookupMethod {
93                    ByLocation,
94                    ByName,
95                    ByList,
96                    MethodNone
97            }
98            
99            
100          String dialogMessage = "";          String dialogMessage = "";
101          ProgressDialog dialog;          ProgressDialog dialog;
102          LocationLookup locator = null;          LocationLookup locationLookup = null;
103          LocatorTask locatorTask;          FindStationsTask findStationsTask;
104          StationsFetchedHandler stationsFetched = new StationsFetchedHandler();          StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
105                    
106          GeoPair location = new GeoPair();          GeoPair location = new GeoPair();
107            
108            boolean isLaunchedforShortcut;
109          boolean isRunning = false;          boolean isRunning = false;
110          List<StationBean> stations = new ArrayList<StationBean>();          StationBean stations = new StationBean();
111                    
112          StationProvider stationProvider = ProviderFactory.getStationProvider();          StationProvider stationProvider = ProviderFactory.getStationProvider();
113                                    
# Line 73  public class StationList extends ListAct Line 115  public class StationList extends ListAct
115                    
116          FavoritesMenu contextMenu = new FavoritesMenu();          FavoritesMenu contextMenu = new FavoritesMenu();
117          IntSet favorites = new IntSet();          IntSet favorites = new IntSet();
118            
119          static enum LookupMethod {          WelcomeScreen.ListType listType;
                 ByLocation,  
                 ByName,  
                 ByList,  
                 MethodNone  
         }  
           
120          SharedPreferences prefs;          SharedPreferences prefs;
121                    
122          ///////////////////////////////////////////////////////////////////////////////////////////          ///////////////////////////////////////////////////////////////////////////////////////////
123          //Activity call backs          //Activity call backs
124                    
125          @SuppressWarnings("unchecked")  
126          @Override          @Override
127          public void onCreate(Bundle savedInstanceState) {          public void onCreate(Bundle savedInstanceState) {
128                  super.onCreate(savedInstanceState);                  super.onCreate(savedInstanceState);
129                  setContentView(R.layout.main);                  setContentView(R.layout.stationlist);
130                                    
131                                    
132                  adapter = new StationListAdapter(this);                  adapter = new StationListAdapter(this);
# Line 99  public class StationList extends ListAct Line 135  public class StationList extends ListAct
135                  ListView lv = getListView();                  ListView lv = getListView();
136                  lv.setOnCreateContextMenuListener(contextMenu);                  lv.setOnCreateContextMenuListener(contextMenu);
137                                    
138                  locator = new LocationLookup(this, stationsFetched);                  locationLookup = new LocationLookup(this, stationsFetched);
139                                    
140    
141                  prefs = getSharedPreferences("TrainStation", 0);                  prefs = getSharedPreferences("TrainStation", 0);
# Line 108  public class StationList extends ListAct Line 144  public class StationList extends ListAct
144                          favorites.fromString(favoriteString);                          favorites.fromString(favoriteString);
145                  }                  }
146                                    
147                    listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type");
148                    setTitle();
149                    
150                    isLaunchedforShortcut = getIntent().getBooleanExtra("shortcut", false);
151                    
152                    ProviderFactory.purgeOldEntries(); //cleanup before fetching more data
153                    
154                  if (savedInstanceState == null) {                  if (savedInstanceState == null) {
155                          startLookup();  
156                            
157                            switch (listType) {
158                            case ListNearest:
159                                    startLookup();
160                                    break;
161                            case ListSearch:                                
162                                    showDialog(DLG_STATIONNAME);
163                                    break;
164                            case ListFavorites:
165                                    startFavoriteLookup();
166                                    break;
167                            default:
168                                    // Not possible !?!
169                            }
170                            
171                  } else {                  } else {
172                          stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");                          stations = (StationBean) savedInstanceState.getSerializable("stations");
173                          adapter.setStations(stations);                          adapter.setStations(stations);
174                          location = (GeoPair) savedInstanceState.getSerializable("location");                          location = (GeoPair) savedInstanceState.getSerializable("location");
175                  }                  }
176                    
177            }
178            
179            
180    
181    
182    
183    
184            @Override
185            protected void onDestroy() {
186                    super.onDestroy();
187                    
188                    isRunning = false;
189                    
190                    if (locationLookup != null) {
191                            locationLookup.stopSearch();
192                    }
193                    if (findStationsTask != null) {
194                            findStationsTask.cancel(true);
195                    }              
196          }          }
197    
198            
199            protected void setTitle() {
200                    String dialogTitle = getResources().getString(app_name);
201                    switch (listType) {
202                    case ListNearest:
203                            dialogTitle += " - " + getString(stationlist_nearbystations);
204                            break;
205                    case ListSearch:
206                            dialogTitle += " - " + getString(stationlist_search);
207                            break;
208                    case ListFavorites:
209                            dialogTitle += " - " + getString(stationlist_favorites);
210                            break;
211                    default:
212                            dialogTitle = "";//not possible                                
213                    }
214            
215                    setTitle(dialogTitle);
216                    
217            }
218            
219                    
220    
221      @Override      @Override
222      public void onSaveInstanceState(Bundle outState)      public void onSaveInstanceState(Bundle outState)
223      {      {
224          if (dialog != null && dialog.isShowing())          if (dialog != null && dialog.isShowing())
225                  dialog.dismiss();                  dialog.dismiss();
226          outState.putSerializable("stations", (ArrayList<StationBean>) stations);          outState.putSerializable("stations", (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, "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");  
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 (StationEntry st : stations.entries ) {
258                                  stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );                                  stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
259                          }                          }
260                                                    
# 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 274  public class StationList extends ListAct Line 373  public class StationList extends ListAct
373          protected void onListItemClick(ListView l, View v, int position, long id) {          protected void onListItemClick(ListView l, View v, int position, long id) {
374                  super.onListItemClick(l, v, position, id);                  super.onListItemClick(l, v, position, id);
375                                                                    
376                  StationBean station = stations.get(position);                  StationEntry station = stations.entries.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);                  showDialog(DLG_PROGRESS);
397                                    
398                  locator.locateStations();                  locationLookup.locateStations();
399                  stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000);                  stationsFetched.sendEmptyMessageDelayed(LookupStates.LOCATIONFIXTIMEOUT.ordinal(), 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);                  showDialog(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);                          showDialog(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);                  showDialog(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) {  
                   
                 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);  
                 }  
437                                    
                 return sb.toString();  
         }  
           
438                    
439          ////////////////////////////////////////////////////////////////////////////          ////////////////////////////////////////////////////////////////////////////
440          // Inner classes          // Inner classes
# Line 373  public class StationList extends ListAct Line 442  public class StationList extends ListAct
442          class StationsFetchedHandler extends Handler {          class StationsFetchedHandler extends Handler {
443                  @Override                  @Override
444                  public void handleMessage(Message msg) {                  public void handleMessage(Message msg) {
445                            Log.e("Handler", "WHAT:" + msg.what);
446                            
447                            LookupStates state = LookupStates.values()[msg.what];
448    
449                          switch (msg.what) {                          switch (state) {
450                          case GOTLOCATION:                          case GOTLOCATION:
451                                  dismissDialog(DLG_PROGRESS);                                  dismissDialog(DLG_PROGRESS);
452                                                                    
453                                  startLocatorTask();                                  startLocatorTask();
454                                  location = GeoPair.fromLocation( locator.getLocation() );                                  location = GeoPair.fromLocation( locationLookup.getLocation() );
455                                                                    
456                                  break;                                  break;
457    
458                          case NOPROVIDER:                          case NOPROVIDER:
459                                  dismissDialog(DLG_PROGRESS);                                  dismissDialog(DLG_PROGRESS);
460                                  MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps.");                                  MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider), true );
461                                    //StationList.this.finish();
462                                  break;                                  break;
463                            case GPS_SAT_COUNT:
464                                    int count = msg.arg1;
465                                    String dialogMessage = getString( stationlist_waitforlocation ) + "\n" + getString( stationlist_satellitecount ) + ": " + count;
466                                    dialog.setMessage( dialogMessage );
467                                    return; //abort immediately
468                          case LOCATIONFIXTIMEOUT:                                                          case LOCATIONFIXTIMEOUT:                                
469                                  if (isRunning) {                                  if (isRunning) {
470                                          locator.stopSearch();                                          locationLookup.stopSearch();
471                                          if (locator.hasLocation()) {                                          if (locationLookup.hasLocation()) {
472                                                  stationsFetched.sendEmptyMessage( GOTLOCATION );                                                  stationsFetched.sendEmptyMessage(  LookupStates.GOTLOCATION.ordinal() );
473                                          } else {                                                                                          } else {                                                
474                                                  dismissDialog(DLG_PROGRESS);                                                  dismissDialog(DLG_PROGRESS);
475                                                                                                    
476                                                  AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                                                                  AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                
477                                                  builder.setMessage("Location fix timed out");                                                  builder.setMessage(  getString( stationlist_gpstimeout) );
478                                                  builder.setCancelable(true);                                                  builder.setCancelable(true);
479                                                  builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {                                                  builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
480                                                          public void onClick(DialogInterface dialog, int id) {                                                          public void onClick(DialogInterface dialog, int id) {
481                                                                  dialog.dismiss();                                                                  dialog.dismiss();
482                                                                  startLookup();                                                                  startLookup();
483                                                                                                                                    
484                                                          }                                                          }
485                                                  });                                                  });
486                                                  builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {                                                  builder.setNegativeButton( getString(generic_cancel), new DialogInterface.OnClickListener() {
487                                                          public void onClick(DialogInterface dialog, int id) {                                                          public void onClick(DialogInterface dialog, int id) {
488                                                                  dialog.dismiss();                                                                  dialog.dismiss();
489                                                          }                                                                                                                }                                                      
490                                                  });                                                                                                                                              });
491                                                  builder.show();                                                  builder.show();
492    
493                                          }                                          }
494                                  }                                  }
# Line 421  public class StationList extends ListAct Line 499  public class StationList extends ListAct
499          };          };
500    
501                    
502          class LocatorTask extends AsyncTask<Void,Void,Void> {          class FindStationsTask extends AsyncTask<Void,Void,Void> {
503                                    
504                  LookupMethod method = LookupMethod.MethodNone;                  LookupMethod method = LookupMethod.MethodNone;
                 boolean success;  
505                  String name;                  String name;
506                  Location loc;                  Location loc;
507                  String ids;                  String ids;
508                                    
509                  public void searchByName(String n, Location l) {                  public void searchByName(String n) {
510                                                    
511                          method = LookupMethod.ByName;                          method = LookupMethod.ByName;
                         loc = l;  
512                          name = n;                          name = n;
513                  }                  }
514                                    
# Line 441  public class StationList extends ListAct Line 517  public class StationList extends ListAct
517                          loc = l;                          loc = l;
518                  }                  }
519                                    
520                  public void searchByIds(String id, Location l) {                  public void searchByIds(String id) {
521                                                    
522                          method = LookupMethod.ByList;                          method = LookupMethod.ByList;
                         loc = l;  
523                          ids = id;                          ids = id;
524                  }                  }
525                                    
# Line 458  public class StationList extends ListAct Line 533  public class StationList extends ListAct
533                                    
534                  @Override                  @Override
535                  protected Void doInBackground(Void... params) {                  protected Void doInBackground(Void... params) {
536                    
537                          if (method.equals(LookupMethod.ByLocation))                          switch (method) {
538                                  success = stationProvider.lookupStations(loc);                          case ByLocation:
539                                                            stations = stationProvider.lookupStations(loc);
540                          if (method.equals(LookupMethod.ByName))                                  break;
541                                  success = stationProvider.lookupStationsByName(name);                          case ByName:
542                                                            stations = stationProvider.lookupStationsByName(name);
543                          if (method.equals(LookupMethod.ByList))                                  break;
544                                  success = stationProvider.lookupStationsByIds(ids);                          case ByList:
545                                                            stations = stationProvider.lookupStationsByIds(ids);
546                          Location dummy = new Location("gps");                                  break;
547                          List<StationBean> stations = stationProvider.getStations();                          default:
548                                    stations = null; // not possible        
549                            }
550                                                    
                         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) );  
                                 }  
                         }                                                
551                                                    
552                          return null;                          return null;
553                  }                  }
# Line 490  public class StationList extends ListAct Line 557  public class StationList extends ListAct
557                          super.onPostExecute(result);                          super.onPostExecute(result);
558                          dialog.dismiss();                          dialog.dismiss();
559                                                    
560                          if (success) {                                                    
561                                  if (stationProvider.getStations().size() == 0)                          if (stations != null) {                        
562                                          MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?!                                  if (stations.entries.size() == 0) {
563                                  stations = stationProvider.getStations();                                          showMessageAndClose(getString(stationlist_nostations));
564                                    }
565    
566                                    StationList.this.getListView().invalidateViews();
567                                  adapter.setStations( stations );                                                                  adapter.setStations( stations );                                
568                                                                    
569                                    
570                          } else { //communication or parse errors                          } else { //communication or parse errors
571                                  AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                                                  AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                
572                                  builder.setMessage("Error on finding nearby stations");                                  builder.setMessage(getString(stationlist_fetcherror));                          
573                                  builder.setCancelable(true);                                  builder.setCancelable(true);
574                                  builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {                                  builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
575                                          public void onClick(DialogInterface dialog, int id) {                                          public void onClick(DialogInterface dialog, int id) {
576                                                  dialog.dismiss();                                                  dialog.dismiss();
577                                                                                                    
578                                                  stationsFetched.post( new Runnable() {                                                  Runnable runner = null;
579                                                          @Override                                                  switch (method) {
580                                                          public void run() {                                                  case ByLocation:
581                                                                  startLocatorTask();                                                                                                                      runner = new Runnable() {
582                                                          }                                                                  @Override
583                                                  });                                                                  public void run() {
584                                                                            startLocatorTask();                                                            
585                                                                    }
586                                                            };
587                                                            break;
588                                                    case ByName:
589                                                            runner = new Runnable() {
590                                                                    @Override
591                                                                    public void run() {
592                                                                            startNameSearch( FindStationsTask.this.name );
593                                                                    }
594                                                            };
595                                                            break;
596                                                    case ByList:
597                                                            runner = new Runnable() {
598                                                                    @Override
599                                                                    public void run() {
600                                                                            startFavoriteLookup();
601                                                                    }
602                                                            };
603                                                            break;
604                                                    }
605                                                    
606                                                    stationsFetched.post( runner );
607                                          }                                          }
608                                  });                                  });
609                                  builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {                                  builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
610                                          public void onClick(DialogInterface dialog, int id) {                                          public void onClick(DialogInterface dialog, int id) {
611                                                  dialog.dismiss();                                                  dialog.dismiss();
612                                                    StationList.this.finish();
613                                          }                                                                                                }                                                      
614                                  });                                                                                                                              });
615                                  builder.show();                                                          
616                                    builder.show();
617                          }                          }
618                  }                  }
619          }          }
# Line 535  public class StationList extends ListAct Line 631  public class StationList extends ListAct
631                                                                                                    
632                          AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;                          AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
633                          selectedPosition = info.position;                          selectedPosition = info.position;
634                          int stationID = stations.get(selectedPosition).getId();                          int stationID = stations.entries.get(selectedPosition).getId();
635    
636                          if (!favorites.hasInt(stationID)) {                          if (!favorites.contains(stationID)) {
637                                  menu.add(0, FAVORITES_ADD, 0, "Add to favorites");                                  menu.add(0, FAVORITES_ADD, 0, getString(stationlist_addfavorite) );
638                          } else {                          } else {
639                                  menu.add(0, FAVORITES_REMOVE, 0, "Remove from favorites");                                  menu.add(0, FAVORITES_REMOVE, 0, getString(stationlist_removefavorite) );
640                          }                          }
641                                                    
642                  }                  }
643                                    
644                  public void onContextItemSelected(MenuItem item) {                  public void onContextItemSelected(MenuItem item) {
645                          StationBean sb = stations.get(selectedPosition);                          StationEntry sb = stations.entries.get(selectedPosition);
646                                                    
647                          int stationID = sb.getId();                          int stationID = sb.getId();
648                          if (item.getItemId() == FAVORITES_ADD) {                          if (item.getItemId() == FAVORITES_ADD) {
649                                  favorites.add(stationID);                                  favorites.add(stationID);
650                                  Toast.makeText(StationList.this, "Station added", Toast.LENGTH_SHORT).show();                                  Toast.makeText(StationList.this, getString(stationlist_stationadded), Toast.LENGTH_SHORT).show();
651                          } else {                          } else {
652                                    
653                                  favorites.remove(stationID);                                  favorites.remove(stationID);
654                                  Toast.makeText(StationList.this, "Station removed", Toast.LENGTH_SHORT).show();                                  Toast.makeText(StationList.this, getString(stationlist_stationremoved), Toast.LENGTH_SHORT).show();
655                                    
656                                    
657                                    if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) {
658                                            stations.entries.remove(selectedPosition);
659                                            adapter.notifyDataSetChanged();
660                                    }
661                          }                          }
662                          Editor ed = prefs.edit();                          Editor ed = prefs.edit();
663                          ed.putString("favorites", favorites.toString());                          ed.putString("favorites", favorites.toString());

Legend:
Removed from v.439  
changed lines
  Added in v.1142

  ViewVC Help
Powered by ViewVC 1.1.20