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

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

  ViewVC Help
Powered by ViewVC 1.1.20