/[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 371 by torben, Wed Sep 30 19:09:59 2009 UTC revision 1150 by torben, Fri Oct 1 17:33:30 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;
41  import android.app.ProgressDialog;  import android.app.ProgressDialog;
42  import android.content.DialogInterface;  import android.content.DialogInterface;
43  import android.content.Intent;  import android.content.Intent;
44  import android.location.Address;  import android.content.SharedPreferences;
45  import android.location.Geocoder;  import android.content.SharedPreferences.Editor;
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;
49  import android.os.Handler;  import android.os.Handler;
50  import android.os.Message;  import android.os.Message;
51  import android.util.Log;  import android.view.ContextMenu;
52    import android.view.LayoutInflater;
53  import android.view.Menu;  import android.view.Menu;
54  import android.view.MenuItem;  import android.view.MenuItem;
55  import android.view.View;  import android.view.View;
56    import android.view.ContextMenu.ContextMenuInfo;
57    import android.view.View.OnCreateContextMenuListener;
58    import android.widget.AdapterView;
59    import android.widget.EditText;
60  import android.widget.ListView;  import android.widget.ListView;
61    import android.widget.Toast;
62    import dk.thoerup.android.traininfo.common.StationBean;
63    import dk.thoerup.android.traininfo.common.StationBean.StationEntry;
64  import dk.thoerup.traininfo.provider.ProviderFactory;  import dk.thoerup.traininfo.provider.ProviderFactory;
65  import dk.thoerup.traininfo.provider.StationProvider;  import dk.thoerup.traininfo.provider.StationProvider;
66  import dk.thoerup.traininfo.stationmap.GeoPair;  import dk.thoerup.traininfo.stationmap.GeoPair;
67  import dk.thoerup.traininfo.stationmap.StationMapView;  import dk.thoerup.traininfo.stationmap.StationMapView;
68    import dk.thoerup.traininfo.util.IntSet;
69  import dk.thoerup.traininfo.util.MessageBox;  import dk.thoerup.traininfo.util.MessageBox;
70    
71  public class StationList extends ListActivity  {  public class StationList extends ListActivity  {
         public static final int GOTLOCATION = 1001;  
         public static final int GOTSTATIONLIST = 1002;  
         public static final int NOPROVIDER = 1003;  
         public static final int LOCATIONFIXTIMEOUT = 1004;  
           
         public static final int OPTIONS_MAP = 2001;  
         public static final int OPTIONS_ABOUT = 2002;  
72    
73                    
         public static final int DLG_PROGRESS = 1001;  
74                    
75          /** Called when the activity is first created. */          public static final int OPTIONS_MAP = 2003;
76            public static final int OPTIONS_GPSINFO = 2004;
77            
78            public static final int DLG_PROGRESS = 3001;
79            public static final int DLG_STATIONNAME = 3002;
80            
81            
82            public static final int GPS_TIMEOUT_MS = 15000; //how long are we willing to wait for gps fix -in milliseconds
83            
84            
85            static enum LookupMethod {
86                    ByLocation,
87                    ByName,
88                    ByList,
89                    MethodNone
90            }
91            
92            
93          String dialogMessage = "";          String dialogMessage = "";
94          ProgressDialog dialog;          ProgressDialog dialog;
95          LocationLookup locator = null;          LocationLookup locationLookup = null;
96          LocatorTask locatorTask;          FindStationsTask findStationsTask;
97            StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
98                    
99          boolean isRunning = false;          //GeoPair location = new GeoPair();
100          List<StationBean> stations = new ArrayList<StationBean>();  
101            boolean isLaunchedforShortcut;
102    
103            StationBean stations = new StationBean();
104                    
105          StationProvider stationProvider = ProviderFactory.getStationProvider();          StationProvider stationProvider = ProviderFactory.getStationProvider();
106                    
107            StationListAdapter adapter = null;
108                    
109            FavoritesMenu contextMenu = new FavoritesMenu();
110            IntSet favorites = new IntSet();
111    
112            WelcomeScreen.ListType listType;
113            SharedPreferences prefs;
114                            
115            ///////////////////////////////////////////////////////////////////////////////////////////
116            //Activity call backs
117                    
118          StationListAdapter adapter = null;  
         @SuppressWarnings("unchecked")  
119          @Override          @Override
120          public void onCreate(Bundle savedInstanceState) {          public void onCreate(Bundle savedInstanceState) {
121                  super.onCreate(savedInstanceState);                  super.onCreate(savedInstanceState);
122                  setContentView(R.layout.main);                  setContentView(R.layout.stationlist);
123                                    
124                                    
125                  adapter = new StationListAdapter(this);                  adapter = new StationListAdapter(this);
126                  setListAdapter(adapter);                  setListAdapter(adapter);
127                                    
128                  locator = new LocationLookup(this, stationsFetched);                  ListView lv = getListView();
129                    lv.setOnCreateContextMenuListener(contextMenu);
130                    
131                    locationLookup = new LocationLookup(this);
132                    
133    
134                    prefs = getSharedPreferences("TrainStation", 0);
135                    String favoriteString = prefs.getString("favorites", "");
136                    if (! favoriteString.equals("") ) {
137                            favorites.fromString(favoriteString);
138                    }
139                    
140                    listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type");
141                    setTitle();
142                    
143                    isLaunchedforShortcut = getIntent().getBooleanExtra("shortcut", false);
144                    
145                    ProviderFactory.purgeOldEntries(); //cleanup before fetching more data
146                    
147                  if (savedInstanceState == null) {                  if (savedInstanceState == null) {
148                          startLookup();  
149                            
150                            switch (listType) {
151                            case ListNearest:
152                                    startLookup();
153                                    break;
154                            case ListSearch:                                
155                                    showDialog(DLG_STATIONNAME);
156                                    break;
157                            case ListFavorites:
158                                    startFavoriteLookup();
159                                    break;
160                            default:
161                                    // Not possible !?!
162                            }
163                            
164                  } else {                  } else {
165                          stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");                          stations = (StationBean) savedInstanceState.getSerializable("stations");
166                          adapter.setStations(stations);                          adapter.setStations(stations);
167                  }                  }
168                    
169            }
170            
171            
172    
173    
174    
175    
176            @Override
177            protected void onDestroy() {
178                    super.onDestroy();
179                    
180                    
181                    if (locationLookup != null) {
182                            locationLookup.stopSearch();
183                    }
184                    if (findStationsTask != null) {
185                            findStationsTask.cancel(true);
186                    }              
187          }          }
188    
189            
190            protected void setTitle() {
191                    String dialogTitle = getResources().getString(app_name);
192                    switch (listType) {
193                    case ListNearest:
194                            dialogTitle += " - " + getString(stationlist_nearbystations);
195                            break;
196                    case ListSearch:
197                            dialogTitle += " - " + getString(stationlist_search);
198                            break;
199                    case ListFavorites:
200                            dialogTitle += " - " + getString(stationlist_favorites);
201                            break;
202                    default:
203                            dialogTitle = "";//not possible                                
204                    }
205            
206                    setTitle(dialogTitle);
207                    
208            }
209            
210                    
211    
212      @Override      @Override
213      public void onSaveInstanceState(Bundle outState)      public void onSaveInstanceState(Bundle outState)
214      {      {
215          if (dialog != null && dialog.isShowing())          if (dialog != null && dialog.isShowing())
216                  dialog.dismiss();                  dialog.dismiss();
217          outState.putSerializable("stations", (ArrayList<StationBean>) stations);          outState.putSerializable("stations", (StationBean) stations);
218            
219      }      }
220                    
221                    
222    
223          @Override          @Override
224          public boolean onCreateOptionsMenu(Menu menu) {          public boolean onCreateOptionsMenu(Menu menu) {
225                  menu.add(0, OPTIONS_MAP, 0, "Show station map");                  MenuItem item;
226                  menu.add(0, OPTIONS_ABOUT, 0, "About");                  
227                    item = menu.add(0, OPTIONS_MAP, 0, getString(stationlist_stationmap));
228                    item.setIcon(android.R.drawable.ic_menu_mapmode);
229                    
230                    item = menu.add(0, OPTIONS_GPSINFO, 0, getString(stationlist_gpsinfo));
231                    item.setIcon(android.R.drawable.ic_menu_mapmode);              
232                                    
233                  return true;                  return true;
234          }          }
235    
236          @Override          @Override
237          public boolean onOptionsItemSelected(MenuItem item) {          public boolean onOptionsItemSelected(MenuItem item) {
238                  boolean retval;                  boolean retval = true;
239                    
240                    //TODO: Cleanup
241                  switch (item.getItemId()) {                  switch (item.getItemId()) {
242                  case OPTIONS_MAP:                  case OPTIONS_MAP:
243                                                    
244                          Intent intent = new Intent(this,StationMapView.class);                          Intent intent = new Intent(this,StationMapView.class);
                         intent.putExtra("userlocation", GeoPair.fromLocation(locator.getLocation()) );  
245                                                    
246                          ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();                          ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
247                          for (StationBean st : stations ) {                          for (StationEntry st : stations.entries ) {
248                                  stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );                                  stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
249                          }                          }
250                                                    
251                          intent.putExtra("stations", stationPoints);                          intent.putExtra("stations", stationPoints);
252                                                    
253                          startActivity(intent);                          startActivity(intent);
                         retval = true;  
254                          break;                          break;
255                  case OPTIONS_ABOUT:                  case OPTIONS_GPSINFO:
256                          String ver = this.getResources().getString(R.string.app_version);                          Location loc = locationLookup.getLocation();
                           
257                          StringBuffer message = new StringBuffer();                          StringBuffer message = new StringBuffer();
258                          message.append("TrainInfo DK v").append(ver).append("\n");                          message.append( getString(stationlist_locationinfo) ).append(":\n");
259                          message.append("By Torben Nielsen\n");                          if (loc != null) {
260                                    message.append( getString(stationlist_obtainedby) ).append( loc.getProvider() ).append("\n");
261                          MessageBox.showMessage(this, message.toString());                                  message.append( getString(stationlist_accuracy) ).append( (int)loc.getAccuracy()).append("m\n");
262                          retval = true;                                  message.append( getString(stationlist_latitude) ).append( (float)loc.getLatitude()).append("\n");
263                                    message.append( getString(stationlist_longitude) ).append( (float)loc.getLongitude() ).append("\n");
264                            } else {
265                                    message.append( getString(stationlist_nolocation) );
266                            }                      
267                            
268                            MessageBox.showMessage(this, message.toString(), false);
269                          break;                          break;
270                  default:                  default:
271                          retval = super.onOptionsItemSelected(item);                          retval = super.onOptionsItemSelected(item);
# Line 129  public class StationList extends ListAct Line 273  public class StationList extends ListAct
273                                    
274                  return retval;                  return retval;
275          }          }
276            
277            
278    
279            @Override
280            public boolean onContextItemSelected(MenuItem item) {
281                    contextMenu.onContextItemSelected(item);
282                    return true;
283    
284    
285            }
286            
287            public void showMessageAndClose(String message) {
288                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
289                    builder.setMessage(message)
290                    .setCancelable(false)
291                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
292                            public void onClick(DialogInterface dialog, int id) {
293                                    dialog.dismiss();
294                                    StationList.this.finish();
295                            }
296                    })
297                    .show();
298            }
299    
300    
301    
302    
303          @Override          @Override
304          protected Dialog onCreateDialog(int id) {          protected Dialog onCreateDialog(int id) {
305                  switch (id) {                  switch (id) {
306                  case DLG_PROGRESS:                  case DLG_PROGRESS:
307                          ProgressDialog dlg = new ProgressDialog(this);                          ProgressDialog dlg = new ProgressDialog(this);
308                          dlg.setMessage("Wait for location fix");                          dlg.setMessage( getString(stationlist_waitforlocation) );
309                          dlg.setCancelable(false);                          dlg.setCancelable(false);
310                          return dlg;                                              return dlg;                    
311                    case DLG_STATIONNAME:
312                            LayoutInflater factory = LayoutInflater.from(this);
313                            final View rootView = factory.inflate(R.layout.textinput, null);
314                            
315                            
316                            AlertDialog.Builder builder = new AlertDialog.Builder(this);
317                            
318                            builder.setTitle( getString(stationlist_stationsearch) );
319                            builder.setView(rootView);
320                            builder.setCancelable(true);
321                            builder.setPositiveButton( getString(generic_search), new DialogInterface.OnClickListener() {
322                                    public void onClick(DialogInterface dialog, int which) {
323                                            EditText et = (EditText) rootView.findViewById(R.id.EditText);
324                                            dialog.dismiss();
325                                            String search = et.getText().toString().trim();
326                                            if (search.length() >= 2) {
327                                                    startNameSearch(search);
328                                            } else {
329                                                    showMessageAndClose( getString(stationlist_twocharmin) );
330                                            }
331                                    }
332                            });
333                            builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
334                                    public void onClick(DialogInterface dialog, int which) {
335                                            dialog.dismiss();
336                                            StationList.this.finish(); // Close this Activity
337                                    }
338                            });                    
339                            return builder.create();
340                            
341                  default:                  default:
342                          return super.onCreateDialog(id);                                          return super.onCreateDialog(id);                
343                  }                  }
# Line 145  public class StationList extends ListAct Line 345  public class StationList extends ListAct
345          }          }
346                    
347                    
   
348          @Override          @Override
349          protected void onPrepareDialog(int id, Dialog dialog) {          protected void onPrepareDialog(int id, Dialog dialog) {
350                  super.onPrepareDialog(id, dialog);                  super.onPrepareDialog(id, dialog);
# Line 159  public class StationList extends ListAct Line 358  public class StationList extends ListAct
358                          break;                          break;
359                  }                  }
360          }          }
361            
362            @Override
363            protected void onListItemClick(ListView l, View v, int position, long id) {
364                    super.onListItemClick(l, v, position, id);
365                                    
366                    StationEntry station = stations.entries.get(position);
367                    
368                    if (isLaunchedforShortcut == true) {
369                            Intent i = new Intent();
370                            i.putExtra("station", station);
371                            setResult(Activity.RESULT_OK, i);
372                            finish();
373                    } else {                
374                            Intent intent = new Intent(this, DepartureList.class);
375                            intent.putExtra("stationbean", station);
376                            startActivity(intent);
377                    }
378            }
379    
380            /////////////////////////////////////////////////////////////
381            //
382    
383          public void startLookup() {          public void startLookup() {
384                  isRunning = true;                  dialogMessage = getString( stationlist_waitforlocation );
385                  showDialog(DLG_PROGRESS);                  showDialog(DLG_PROGRESS);
386                                    
387                  locator.locateStations();                  locationLookup.locateStations();
388                  stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000);                  stationsFetched.sendEmptyMessageDelayed(0, 500);
389          }          }
390            
391            void startNameSearch(String name) {
392                    dialogMessage = getString( stationlist_findbyname );
393                    showDialog(DLG_PROGRESS);
394    
395                    findStationsTask = new FindStationsTask();
396                    findStationsTask.searchByName(name);
397                    findStationsTask.execute();
398                    
399            }
400            
401            public void startFavoriteLookup() {
402                    
403                    if (favorites.size() > 0) {
404                            dialogMessage = getString( stationlist_loadfavorites );
405                            showDialog(DLG_PROGRESS);
406    
407                            findStationsTask = new FindStationsTask();
408                            findStationsTask.searchByIds( favorites.toString() );
409                            findStationsTask.execute();
410                    } else {
411                            showMessageAndClose( getString( stationlist_nofavorites ) );
412                    }
413            }
414    
415    
416            
417            void startLocatorTask()
418            {
419                    dialogMessage = getString( stationlist_findingnearby );
420                    showDialog(DLG_PROGRESS);              
421                    
422                    findStationsTask = new FindStationsTask();
423                    findStationsTask.searchByLocation( locationLookup.getLocation() );
424                    findStationsTask.execute();    
425            }
426                    
427            
428            ////////////////////////////////////////////////////////////////////////////
429            // Inner classes
430    
431          Handler stationsFetched = new Handler() {          class StationsFetchedHandler extends Handler {
432                  @Override                  @Override
433                  public void handleMessage(Message msg) {                  public void handleMessage(Message msg) {
434    
435                          switch (msg.what) {                          LocationLookup.LookupStates state = locationLookup.getState();
436    
437    
438                            switch (state) {
439                          case GOTLOCATION:                          case GOTLOCATION:
440                                  dismissDialog(DLG_PROGRESS);                                  dismissDialog(DLG_PROGRESS);
441                                    
442                                  startLocatorTask();                                  startLocatorTask();
443                                    
444                                  break;                                  return;
445    
446                          case NOPROVIDER:                          case NOPROVIDER:
447                                  dismissDialog(DLG_PROGRESS);                                  dismissDialog(DLG_PROGRESS);
448                                  MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps.");                                  MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider), true );
449                                  break;                                  //StationList.this.finish();
450                          case LOCATIONFIXTIMEOUT:                                                                  return;
451                                  if (isRunning) {                          }
452                                          locator.stopSearch();  
453                                          if (locator.hasLocation()) {  
454                                                  stationsFetched.sendEmptyMessage( GOTLOCATION );  
455                                          } else {                                                                          if (locationLookup.elapsedTime() >=  GPS_TIMEOUT_MS) {
456                                                  dismissDialog(DLG_PROGRESS);                                  dismissDialog(DLG_PROGRESS);
457                                                    
458                                                  AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                                                  locationLookup.stopSearch();
459                                                  builder.setMessage("GPS fix timed out");  
460                                                  builder.setCancelable(true);                                  if (locationLookup.hasLocation()) {
461                                                  builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {                                          startLocatorTask();
462                                                          public void onClick(DialogInterface dialog, int id) {                                  } else {                                                
463                                                                  dialog.dismiss();                                          AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                
464                                                                  startLookup();                                          builder.setMessage(  getString( stationlist_gpstimeout) );
465                                                                                                            builder.setCancelable(true);
466                                                          }                                          builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
467                                                  });                                                  public void onClick(DialogInterface dialog, int id) {
468                                                  builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {                                                          dialog.dismiss();
469                                                          public void onClick(DialogInterface dialog, int id) {                                                          startLookup();
470                                                                  dialog.dismiss();  
471                                                          }                                                                                                        }
472                                                  });                                                                                                                                      });
473                                                  builder.show();                                          builder.setNegativeButton( getString(generic_cancel), new DialogInterface.OnClickListener() {
474                                                    public void onClick(DialogInterface dialog, int id) {
475                                                            dialog.dismiss();
476                                                            StationList.this.finish(); // Close this Activity
477                                                    }                                                      
478                                            });
479                                            builder.show();
480    
                                         }  
481                                  }                                  }
482                                  break;                          } else {
483                                    if (locationLookup.hasGps()) {
484                                            int count = locationLookup.getSatCount();
485                                            String dialogMessage = getString( stationlist_waitforlocation ) + "\n" + getString( stationlist_satellitecount ) + ": " + count;
486                                            dialog.setMessage( dialogMessage );
487                                    }
488                                    this.sendEmptyMessageDelayed(0, 500);
489                          }                          }
490                          isRunning = false;                          
491                  }                  }
         };  
           
         void startLocatorTask()  
         {  
                 dialogMessage = "Finding nearby stations";  
                 showDialog(DLG_PROGRESS);  
                   
                 locatorTask = new LocatorTask();  
                 locatorTask.execute();    
492          }          }
           
         @Override  
         protected void onListItemClick(ListView l, View v, int position, long id) {  
                 super.onListItemClick(l, v, position, id);  
                                   
                 StationBean station = stations.get(position);  
493    
                 double latitude = station.getLatitude();  
                 double longitude = station.getLongitude();  
494    
495    
496            
497            class FindStationsTask extends AsyncTask<Void,Void,Void> {
498                                    
499                  Intent intent = new Intent(this, DepartureList.class);                  LookupMethod method = LookupMethod.MethodNone;
500                  intent.putExtra("name", station.getName());                  String name;
501                  intent.putExtra("distance", station.getDistance());                  Location loc;
502                  intent.putExtra("latitude", latitude);                  String ids;
                 intent.putExtra("longitude", longitude);  
                 intent.putExtra("stationid", station.getId());  
                 intent.putExtra("address", station.getAddress());  
                 startActivity(intent);  
         }  
   
         String lookupAddress(double latitude, double longitude) {  
503                                    
504                  Geocoder coder = new Geocoder(this, new Locale("da"));                  public void searchByName(String n) {
                 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));  
                         }  
505                                                    
506                            method = LookupMethod.ByName;
507                            name = n;
508                    }
509                    
510                    public void searchByLocation(Location l) {
511                            method = LookupMethod.ByLocation;
512                            loc = l;
513                    }
514                    
515                    public void searchByIds(String id) {
516                                                    
517                  } catch (Exception e) {                          method = LookupMethod.ByList;
518                          Log.e("DepartureList", "geocoder failed", e);                          ids = id;
519                  }                  }
520                                    
                 return sb.toString();  
         }  
           
         class LocatorTask extends AsyncTask<Void,Void,Void> {  
                 boolean success;  
521                  @Override                  @Override
522                  protected void onPreExecute() {                  protected void onPreExecute() {
523    
524                            if (method.equals(LookupMethod.MethodNone))
525                                    throw new RuntimeException("Method not set");
526                          super.onPreExecute();                          super.onPreExecute();
527                  }                  }
528                                    
529                  @Override                  @Override
530                  protected Void doInBackground(Void... params) {                  protected Void doInBackground(Void... params) {
531                          Location loc = locator.getLocation();  
532                          success = stationProvider.lookupStations(loc);                          switch (method) {
533                                                    case ByLocation:
534                                                            stations = stationProvider.lookupStations(loc);
535                          List<StationBean> stations = stationProvider.getStations();                                  break;
536                          for (StationBean station : stations) {                          case ByName:
537                                  String addr = lookupAddress(station.getLatitude(), station.getLongitude());                                  stations = stationProvider.lookupStationsByName(name);
538                                  station.setAddress(addr);                                  break;
539                            case ByList:
540                                    stations = stationProvider.lookupStationsByIds(ids);
541                                    break;
542                            default:
543                                    stations = null; // not possible        
544                          }                          }
545                                                    
546                            
547                          return null;                          return null;
548                  }                  }
549    
# Line 302  public class StationList extends ListAct Line 552  public class StationList extends ListAct
552                          super.onPostExecute(result);                          super.onPostExecute(result);
553                          dialog.dismiss();                          dialog.dismiss();
554                                                    
555                          if (success) {                                                    
556                                  if (stationProvider.getStations().size() == 0)                          if (stations != null) {                        
557                                          MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?!                                  if (stations.entries.size() == 0) {
558                                  stations = stationProvider.getStations();                                          showMessageAndClose(getString(stationlist_nostations));
559                                    }
560    
561                                    StationList.this.getListView().invalidateViews();
562                                  adapter.setStations( stations );                                                                  adapter.setStations( stations );                                
563                                                                    
564                                    
565                          } else { //communication or parse errors                          } else { //communication or parse errors
566                                  AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                                                  AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                
567                                  builder.setMessage("Error on finding nearby stations");                                  builder.setMessage(getString(stationlist_fetcherror));                          
568                                  builder.setCancelable(true);                                  builder.setCancelable(true);
569                                  builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {                                  builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
570                                          public void onClick(DialogInterface dialog, int id) {                                          public void onClick(DialogInterface dialog, int id) {
571                                                  dialog.dismiss();                                                  dialog.dismiss();
572                                                                                                    
573                                                  stationsFetched.post( new Runnable() {                                                  Runnable runner = null;
574                                                          @Override                                                  switch (method) {
575                                                          public void run() {                                                  case ByLocation:
576                                                                  startLocatorTask();                                                                                                                      runner = new Runnable() {
577                                                          }                                                                  @Override
578                                                  });                                                                  public void run() {
579                                                                            startLocatorTask();                                                            
580                                                                    }
581                                                            };
582                                                            break;
583                                                    case ByName:
584                                                            runner = new Runnable() {
585                                                                    @Override
586                                                                    public void run() {
587                                                                            startNameSearch( FindStationsTask.this.name );
588                                                                    }
589                                                            };
590                                                            break;
591                                                    case ByList:
592                                                            runner = new Runnable() {
593                                                                    @Override
594                                                                    public void run() {
595                                                                            startFavoriteLookup();
596                                                                    }
597                                                            };
598                                                            break;
599                                                    }
600                                                    
601                                                    stationsFetched.post( runner );
602                                          }                                          }
603                                  });                                  });
604                                  builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {                                  builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
605                                          public void onClick(DialogInterface dialog, int id) {                                          public void onClick(DialogInterface dialog, int id) {
606                                                  dialog.dismiss();                                                  dialog.dismiss();
607                                                    StationList.this.finish();
608                                          }                                                                                                }                                                      
609                                  });                                                                                                                              });
610                                  builder.show();                                                          
611                                    builder.show();
612                            }
613                    }
614            }
615            
616            
617            class FavoritesMenu implements OnCreateContextMenuListener {
618                    private final static int FAVORITES_ADD = 9001;
619                    private final static int FAVORITES_REMOVE = 9002;
620                    
621                    private int selectedPosition;
622                    
623                    
624                    @Override
625                    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
626                                                    
627                            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
628                            selectedPosition = info.position;
629                            int stationID = stations.entries.get(selectedPosition).getId();
630    
631                            if (!favorites.contains(stationID)) {
632                                    menu.add(0, FAVORITES_ADD, 0, getString(stationlist_addfavorite) );
633                            } else {
634                                    menu.add(0, FAVORITES_REMOVE, 0, getString(stationlist_removefavorite) );
635                            }
636                            
637                    }
638                    
639                    public void onContextItemSelected(MenuItem item) {
640                            StationEntry sb = stations.entries.get(selectedPosition);
641                            
642                            int stationID = sb.getId();
643                            if (item.getItemId() == FAVORITES_ADD) {
644                                    favorites.add(stationID);
645                                    Toast.makeText(StationList.this, getString(stationlist_stationadded), Toast.LENGTH_SHORT).show();
646                            } else {
647                                    
648                                    favorites.remove(stationID);
649                                    Toast.makeText(StationList.this, getString(stationlist_stationremoved), Toast.LENGTH_SHORT).show();
650                                    
651                                    
652                                    if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) {
653                                            stations.entries.remove(selectedPosition);
654                                            adapter.notifyDataSetChanged();
655                                    }
656                          }                          }
657                            Editor ed = prefs.edit();
658                            ed.putString("favorites", favorites.toString());
659                            ed.commit();
660                  }                  }
661          }          }
662  }  }

Legend:
Removed from v.371  
changed lines
  Added in v.1150

  ViewVC Help
Powered by ViewVC 1.1.20