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

Legend:
Removed from v.336  
changed lines
  Added in v.917

  ViewVC Help
Powered by ViewVC 1.1.20