/[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

android/TrainInfo/src/dk/thoerup/traininfo/TrainInfoList.java revision 258 by torben, Mon Aug 10 19:37:18 2009 UTC android/TrainInfo/src/dk/thoerup/traininfo/StationList.java revision 1558 by torben, Fri Jul 8 13:10:53 2011 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfo;  package dk.thoerup.traininfo;
2    
3    import static dk.thoerup.traininfo.R.string.app_name;
4    import static dk.thoerup.traininfo.R.string.generic_cancel;
5    import static dk.thoerup.traininfo.R.string.generic_retry;
6    import static dk.thoerup.traininfo.R.string.stationlist_accuracy;
7    import static dk.thoerup.traininfo.R.string.stationlist_addfavorite;
8    import static dk.thoerup.traininfo.R.string.stationlist_favorites;
9    import static dk.thoerup.traininfo.R.string.stationlist_gpsinfo;
10    import static dk.thoerup.traininfo.R.string.stationlist_gpstimeout;
11    import static dk.thoerup.traininfo.R.string.stationlist_latitude;
12    import static dk.thoerup.traininfo.R.string.stationlist_locationinfo;
13    import static dk.thoerup.traininfo.R.string.stationlist_longitude;
14    import static dk.thoerup.traininfo.R.string.stationlist_nearbystations;
15    import static dk.thoerup.traininfo.R.string.stationlist_nofavorites;
16    import static dk.thoerup.traininfo.R.string.stationlist_nolocationprovider;
17    import static dk.thoerup.traininfo.R.string.stationlist_obtainedby;
18    import static dk.thoerup.traininfo.R.string.stationlist_removefavorite;
19    import static dk.thoerup.traininfo.R.string.stationlist_satellitecount;
20    import static dk.thoerup.traininfo.R.string.stationlist_search;
21    import static dk.thoerup.traininfo.R.string.stationlist_stationadded;
22    import static dk.thoerup.traininfo.R.string.stationlist_stationmap;
23    import static dk.thoerup.traininfo.R.string.stationlist_stationremoved;
24    import static dk.thoerup.traininfo.R.string.stationlist_waitforlocation;
25    
26  import java.util.ArrayList;  import java.util.ArrayList;
 import java.util.List;  
27    
28    import android.app.Activity;
29    import android.app.AlertDialog;
30  import android.app.Dialog;  import android.app.Dialog;
31  import android.app.ListActivity;  import android.app.ListActivity;
32  import android.app.ProgressDialog;  import android.app.ProgressDialog;
33    import android.content.DialogInterface;
34  import android.content.Intent;  import android.content.Intent;
35  import android.os.AsyncTask;  import android.content.SharedPreferences;
36    import android.content.SharedPreferences.Editor;
37    import android.location.Location;
38  import android.os.Bundle;  import android.os.Bundle;
39  import android.os.Handler;  import android.os.Handler;
40  import android.os.Message;  import android.os.Message;
41    import android.text.Editable;
42    import android.text.TextWatcher;
43    import android.util.Log;
44    import android.view.ContextMenu;
45    import android.view.ContextMenu.ContextMenuInfo;
46    import android.view.Menu;
47    import android.view.MenuItem;
48  import android.view.View;  import android.view.View;
49    import android.view.View.OnCreateContextMenuListener;
50    import android.widget.AdapterView;
51  import android.widget.ListView;  import android.widget.ListView;
52    import android.widget.TextView;
53    import android.widget.Toast;
54    import dk.thoerup.android.traininfo.common.StationBean;
55    import dk.thoerup.android.traininfo.common.StationEntry;
56    import dk.thoerup.traininfo.WelcomeScreen.ListType;
57    import dk.thoerup.traininfo.provider.ProviderFactory;
58    import dk.thoerup.traininfo.provider.StationProvider;
59    import dk.thoerup.traininfo.stationmap.GeoPair;
60    import dk.thoerup.traininfo.stationmap.StationMapView;
61    import dk.thoerup.traininfo.util.IntSet;
62  import dk.thoerup.traininfo.util.MessageBox;  import dk.thoerup.traininfo.util.MessageBox;
63    
64  public class TrainInfoList extends ListActivity  {  public class StationList extends ListActivity  {
65          public static final int GOTLOCATION = 1;  
         public static final int GOTSTATIONLIST = 2;  
         public static final int NOPROVIDER = 3;  
         public static final int FIXTIMEOUT = 4;  
         public static final int LOOKUPSTATIONFAILED = 5;  
66                    
         public static final int DLG_PROGRESS = 1;  
67                    
68          /** Called when the activity is first created. */          public static final int OPTIONS_MAP = 103;
69          ProgressDialog dialog;          public static final int OPTIONS_GPSINFO = 104;
70          StationLocator locator = null;          
71          LocatorTask locatorTask = new LocatorTask();          public static final int DLG_PROGRESS = 3001;
72            
73                    
74          boolean isRunning = false;          public static final int GPS_TIMEOUT_MS = 15000; //how long are we willing to wait for gps fix -in milliseconds
75          List<StationBean> stations = new ArrayList<StationBean>();          
76            
77            static enum LookupMethod {
78                    ByLocation,
79                    ByName,
80                    ByList,
81                    MethodNone
82            }
83            
84            
85            String dialogMessage = "";
86            ProgressDialog dialog;
87            LocationLookup locationLookup = null;
88            StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
89                    
90            //GeoPair location = new GeoPair();
91    
92            boolean isLaunchedforShortcut;
93    
94            StationBean stations = new StationBean();
95                    
96            StationProvider stationProvider = ProviderFactory.getStationProvider();
97                    
98          StationListAdapter adapter = null;          StationListAdapter adapter = null;
99          @SuppressWarnings("unchecked")          
100            FavoritesMenu contextMenu = new FavoritesMenu();
101            IntSet favorites = new IntSet();
102    
103            WelcomeScreen.ListType listType;
104            SharedPreferences prefs;
105                            
106            ///////////////////////////////////////////////////////////////////////////////////////////
107            //Activity call backs
108            
109    
110          @Override          @Override
111          public void onCreate(Bundle savedInstanceState) {          public void onCreate(Bundle savedInstanceState) {
112                  super.onCreate(savedInstanceState);                  super.onCreate(savedInstanceState);
113                  setContentView(R.layout.main);                  setContentView(R.layout.stationlist);
114                                    
115                  StationLocator.removeMockLocation(this);                  listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type");
                 //StationLocator.injectMockLocation(this);  
116                                    
117                  adapter = new StationListAdapter(this);                  adapter = new StationListAdapter(this, (listType == ListType.ListNearest) );
118                  setListAdapter(adapter);                  setListAdapter(adapter);
119                                    
120                  locator = new StationLocator(this, stationsFetched);                  ListView lv = getListView();
121                    lv.setOnCreateContextMenuListener(contextMenu);
122                    
123                    locationLookup = new LocationLookup(this);
124                    
125    
126                    prefs = getSharedPreferences("TrainStation", 0);
127                    String favoriteString = prefs.getString("favorites", "");
128                    if (! favoriteString.equals("") ) {
129                            favorites.fromString(favoriteString);
130                    }
131                    
132                    setTitle();
133                    
134                    isLaunchedforShortcut = getIntent().getBooleanExtra("shortcut", false);
135                    
136                    ProviderFactory.purgeOldEntries(); //cleanup before fetching more data
137                    
138                  if (savedInstanceState == null) {                  if (savedInstanceState == null) {
139                          startLookup();  
140                            
141                            switch (listType) {
142                            case ListNearest:
143                                    startNearestLookup();
144                                    break;
145                            case ListSearch:                                
146                                    enableNamesearchField();
147                                    break;
148                            case ListFavorites:
149                                    startFavoriteLookup();
150                                    break;
151                            default:
152                                    // Not possible !?!
153                            }
154                            
155                  } else {                  } else {
156                          stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");                          stations = (StationBean) savedInstanceState.getSerializable("stations");
157                          adapter.setStations(new ArrayList<StationBean>(stations));                          adapter.setStations(stations);
158                    }
159                    
160            }
161            
162            
163    
164    
165    
166    
167            @Override
168            protected void onDestroy() {
169                    super.onDestroy();
170                    
171                    stationsFetched.removeMessages(0);
172                    
173                    
174                    if (locationLookup != null) {
175                            locationLookup.stopSearch();
176                    }
177            
178            }
179    
180            
181            protected void setTitle() {
182                    String dialogTitle = getResources().getString(app_name);
183                    switch (listType) {
184                    case ListNearest:
185                            dialogTitle += " - " + getString(stationlist_nearbystations);
186                            break;
187                    case ListSearch:
188                            dialogTitle += " - " + getString(stationlist_search);
189                            break;
190                    case ListFavorites:
191                            dialogTitle += " - " + getString(stationlist_favorites);
192                            break;
193                    default:
194                            dialogTitle = "";//not possible                                
195                  }                  }
196            
197                    setTitle(dialogTitle);
198                    
199          }          }
200                    
201            
202            public void enableNamesearchField() {
203                    final TextView stationSearch = (TextView) findViewById(R.id.stationsearch);
204                    stationSearch.setVisibility( View.VISIBLE );
205                    stationSearch.addTextChangedListener( new TextWatcher() {
206    
207                            @Override
208                            public void afterTextChanged(Editable s) {
209                                    if (s.length() > 0) {
210                                            startNameLookup( s.toString() );
211                                    } else {
212                                            stations = new StationBean();
213                                            getListView().invalidateViews();
214                                            adapter.setStations( stations );        
215                                    }
216                            }
217    
218                            @Override
219                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
220                            }
221    
222                            @Override
223                            public void onTextChanged(CharSequence s, int start, int before, int count) {
224                            }
225                            
226                    });
227                    
228                    
229            }
230                    
231    
232      @Override      @Override
233      public void onSaveInstanceState(Bundle outState)      public void onSaveInstanceState(Bundle outState)
234      {      {
235          if (dialog != null && dialog.isShowing())          if (dialog != null && dialog.isShowing())
236                  dialog.dismiss();                  dialog.dismiss();
237          outState.putSerializable("stations", (ArrayList<StationBean>) stations);          outState.putSerializable("stations", (StationBean) stations);
238            
239      }      }
240                    
241                    
242    
243          @Override          @Override
244            public boolean onCreateOptionsMenu(Menu menu) {
245                    MenuItem item;
246                    
247                    item = menu.add(0, OPTIONS_MAP, 0, getString(stationlist_stationmap));
248                    item.setIcon(android.R.drawable.ic_menu_mapmode);
249                    
250                    item = menu.add(0, OPTIONS_GPSINFO, 0, getString(stationlist_gpsinfo));
251                    item.setIcon(android.R.drawable.ic_menu_info_details);
252                    boolean hasLoc = (locationLookup.getLocation() != null);
253                    item.setEnabled(hasLoc);
254                    
255                    return true;
256            }
257            
258    
259    
260    
261            @Override
262            public boolean onOptionsItemSelected(MenuItem item) {
263                    boolean retval = true;
264    
265    
266                    switch (item.getItemId()) {
267                    case OPTIONS_MAP:
268                            
269                            if ( stations == null || stations.entries == null || stations.entries.size() == 0 ) {
270                                    Toast.makeText(this, "No stations to show on map", Toast.LENGTH_SHORT).show(); //TODO: Translate
271                                    return true;
272                            }
273                            
274                            Intent intent = new Intent(this,StationMapView.class);
275                            
276                            ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
277                            for (StationEntry st : stations.entries ) {
278                                    stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
279                            }
280                            
281                            intent.putExtra("stations", stationPoints);
282                            
283                            startActivity(intent);
284                            break;
285                    case OPTIONS_GPSINFO:
286                            Location loc = locationLookup.getLocation();
287                            StringBuffer message = new StringBuffer();
288                            message.append( getString(stationlist_locationinfo) ).append(":\n");
289                            
290                            message.append( getString(stationlist_obtainedby) ).append( loc.getProvider() ).append("\n");
291                            message.append( getString(stationlist_accuracy) ).append( (int)loc.getAccuracy()).append("m\n");
292                            message.append( getString(stationlist_latitude) ).append( (float)loc.getLatitude()).append("\n");
293                            message.append( getString(stationlist_longitude) ).append( (float)loc.getLongitude() ).append("\n");
294                                                    
295                            
296                            MessageBox.showMessage(this, message.toString(), false);
297                            break;
298                    default:
299                            retval = super.onOptionsItemSelected(item);
300                    }
301                    
302                    return retval;
303            }
304            
305            
306    
307            @Override
308            public boolean onContextItemSelected(MenuItem item) {
309                    contextMenu.onContextItemSelected(item);
310                    return true;
311    
312    
313            }
314            
315            public void showMessageAndClose(String message) {
316                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
317                    builder.setMessage(message)
318                    .setCancelable(false)
319                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
320                            public void onClick(DialogInterface dialog, int id) {
321                                    dialog.dismiss();
322                                    StationList.this.finish();
323                            }
324                    })
325                    .show();
326            }
327    
328    
329    
330    
331            @Override
332          protected Dialog onCreateDialog(int id) {          protected Dialog onCreateDialog(int id) {
333                  switch (id) {                  switch (id) {
334                  case DLG_PROGRESS:                  case DLG_PROGRESS:
335                          ProgressDialog dlg = new ProgressDialog(this);                          ProgressDialog dlg = new ProgressDialog(this);
336                          dlg.setMessage("Wait for location fix");                          dlg.setMessage( getString(stationlist_waitforlocation) );
337                          dlg.setCancelable(false);                          dlg.setCancelable(false);
338                          return dlg;                          return dlg;                    
339                            
340                  default:                  default:
341                          return super.onCreateDialog(id);                                          return super.onCreateDialog(id);                
342                  }                  }
# Line 81  public class TrainInfoList extends ListA Line 344  public class TrainInfoList extends ListA
344          }          }
345                    
346                    
   
347          @Override          @Override
348          protected void onPrepareDialog(int id, Dialog dialog) {          protected void onPrepareDialog(int id, Dialog dialog) {
349                  super.onPrepareDialog(id, dialog);                  super.onPrepareDialog(id, dialog);
350                  switch (id) {                  switch (id) {
351                  case DLG_PROGRESS:                  case DLG_PROGRESS:
352                          this.dialog = (ProgressDialog) dialog;                          this.dialog = (ProgressDialog) dialog;
353                            if (!dialogMessage.equals("")) {
354                                    this.dialog.setMessage(dialogMessage);
355                                    dialogMessage = "";
356                            }
357                          break;                          break;
358                  }                  }
359          }          }
360            
361            @Override
362            protected void onListItemClick(ListView l, View v, int position, long id) {
363                    super.onListItemClick(l, v, position, id);
364                                    
365                    StationEntry station = stations.entries.get(position);
366                    
367                    if (isLaunchedforShortcut == true) {
368                            Intent i = new Intent();
369                            i.putExtra("station", station);
370                            setResult(Activity.RESULT_OK, i);
371                            finish();
372                    } else {                
373                            Intent intent = new Intent(this, DepartureList.class);
374                            intent.putExtra("stationbean", station);
375                            startActivity(intent);
376                    }
377            }
378    
379            /////////////////////////////////////////////////////////////
380            //
381    
382          public void startLookup() {          public void startNearestLookup() {
383                  isRunning = true;                  dialogMessage = getString( stationlist_waitforlocation );
384                  showDialog(DLG_PROGRESS);                  showDialog(DLG_PROGRESS);
385                                    
386                  locator.locateStations();                  locationLookup.locateStations();
387                  stationsFetched.sendEmptyMessageDelayed(FIXTIMEOUT, 20000);                  stationsFetched.sendEmptyMessageDelayed(0, 500);
388            }
389            
390            void startNameLookup(String name) {
391                    
392                    stations = stationProvider.lookupStationsByName(name);
393                    getListView().invalidateViews();
394                    adapter.setStations( stations );                                
395            }
396            
397            public void startFavoriteLookup() {
398                    
399                    if (favorites.size() > 0) {
400                            
401                            stations = stationProvider.lookupStationsByIds( favorites.toString() );
402                            getListView().invalidateViews();
403                            adapter.setStations( stations );                
404                            
405                            
406                    } else {
407                            showMessageAndClose( getString( stationlist_nofavorites ) );
408                    }
409          }          }
410    
411    
412          Handler stationsFetched = new Handler() {          
413            void startNearestLookupPhase2()
414            {      
415                    stations = stationProvider.lookupStationsByLocation( locationLookup.getLocation() );
416                    getListView().invalidateViews();
417                    adapter.setStations( stations );
418            }
419                    
420            
421            ////////////////////////////////////////////////////////////////////////////
422            // Inner classes
423    
424            class StationsFetchedHandler extends Handler {
425                  @Override                  @Override
426                  public void handleMessage(Message msg) {                  public void handleMessage(Message msg) {
427                          switch (msg.what) {  
428                            LocationLookup.LookupStates state = locationLookup.getState();
429    
430    
431                            switch (state) {
432                          case GOTLOCATION:                          case GOTLOCATION:
433                                  dialog.setMessage("Finding nearby stations");                                  dismissDialog(DLG_PROGRESS);
434                                  locatorTask.execute();  
435                                  break;                                  startNearestLookupPhase2();
436                          case GOTSTATIONLIST:  
437                                  dialog.dismiss();                                  return;
438                                  if (locator.getStations().size() == 0)  
                                         MessageBox.showMessage(TrainInfoList.this,"Error loading station list!");  
                                 stations = locator.getStations();  
                                 adapter.setStations( stations );  
                                 break;  
439                          case NOPROVIDER:                          case NOPROVIDER:
440                                  dialog.dismiss();                                  dismissDialog(DLG_PROGRESS);
441                                  MessageBox.showMessage(TrainInfoList.this,"No location provider enabled. Plase enable gps.");                                  MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider), true );
442                                  break;                                  //StationList.this.finish();
443                          case FIXTIMEOUT:                                  return;
444                                  dialog.dismiss();                          case IDLE:
445                                  if (isRunning) {                                  Log.e("TrainInfo", "How did this happen ???");
446                                          locator.abortLocationListener();                                  dismissDialog(DLG_PROGRESS); // how did we get here ??
447                                          MessageBox.showMessage(TrainInfoList.this,"GPS fix timed out");                                  return;
448                                    
449                            }
450    
451    
452    
453                            if (locationLookup.elapsedTime() >=  GPS_TIMEOUT_MS) {
454                                    dismissDialog(DLG_PROGRESS);
455    
456    
457                                    locationLookup.stopSearch();
458    
459                                    if (locationLookup.hasLocation()) {
460                                            startNearestLookupPhase2();
461                                    } else {                                                
462                                            AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                
463                                            builder.setMessage(  getString( stationlist_gpstimeout) );
464                                            builder.setCancelable(true);
465                                            builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
466                                                    public void onClick(DialogInterface dialog, int id) {
467                                                            dialog.dismiss();
468                                                            startNearestLookup();
469    
470                                                    }
471                                            });
472                                            builder.setNegativeButton( getString(generic_cancel), new DialogInterface.OnClickListener() {
473                                                    public void onClick(DialogInterface dialog, int id) {
474                                                            dialog.dismiss();
475                                                            StationList.this.finish(); // Close this Activity
476                                                    }                                                      
477                                            });
478                                            builder.show();
479    
480                                  }                                  }
481                                  break;                          } else {
482                          case LOOKUPSTATIONFAILED:                                  if (locationLookup.hasGps()) {
483                                  dialog.dismiss();                                          int count = locationLookup.getSatCount();
484                                  MessageBox.showMessage(TrainInfoList.this,"Error on finding nearby stations");                                          String dialogMessage = getString( stationlist_waitforlocation ) + "\n" + getString( stationlist_satellitecount ) + ": " + count;
485                                  break;                                          dialog.setMessage( dialogMessage );
486                                    }
487                                    this.sendEmptyMessageDelayed(0, 500);
488                          }                          }
489                          isRunning = false;                          
490                  }                  }
491          };          }
492            
493            
494    
495                    
496          @Override          class FavoritesMenu implements OnCreateContextMenuListener {
497          protected void onListItemClick(ListView l, View v, int position, long id) {                  private final static int FAVORITES_ADD = 9001;
498                  super.onListItemClick(l, v, position, id);                  private final static int FAVORITES_REMOVE = 9002;
499                                    
500                    private int selectedPosition;
501                                    
                 StationBean station = stations.get(position);  
502                                    
                   
                 Intent intent = new Intent(this, DepartureList.class);  
                 intent.putExtra("name", station.getName());  
                 intent.putExtra("address", station.getAddress());  
                 intent.putExtra("distance", station.getDistance());  
                 intent.putExtra("latitude", station.getLatitude());  
                 intent.putExtra("longitude", station.getLongitude());  
                 startActivity(intent);  
         }  
   
           
         class LocatorTask extends AsyncTask<Void,Void,Void> {  
503                  @Override                  @Override
504                  protected void onPreExecute() {                  public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
505                                                    
506                          super.onPreExecute();                          AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
507                            selectedPosition = info.position;
508                            int stationID = stations.entries.get(selectedPosition).getId();
509    
510                            if (!favorites.contains(stationID)) {
511                                    menu.add(0, FAVORITES_ADD, 0, getString(stationlist_addfavorite) );
512                            } else {
513                                    menu.add(0, FAVORITES_REMOVE, 0, getString(stationlist_removefavorite) );
514                            }
515                            
516                  }                  }
517                                    
518                  @Override                  public void onContextItemSelected(MenuItem item) {
519                  protected Void doInBackground(Void... params) {                          StationEntry sb = stations.entries.get(selectedPosition);
                         locator.findNearestStations();  
520                                                    
521                          return null;                          int stationID = sb.getId();
522                  }                          if (item.getItemId() == FAVORITES_ADD) {
523                                    favorites.add(stationID);
524                  @Override                                  Toast.makeText(StationList.this, getString(stationlist_stationadded), Toast.LENGTH_SHORT).show();
525                  protected void onPostExecute(Void result) {                          } else {
526                          super.onPostExecute(result);                                  
527                                    favorites.remove(stationID);
528                                    Toast.makeText(StationList.this, getString(stationlist_stationremoved), Toast.LENGTH_SHORT).show();
529                                    
530                                    
531                                    if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) {
532                                            stations.entries.remove(selectedPosition);
533                                            adapter.notifyDataSetChanged();
534                                    }
535                            }
536                            Editor ed = prefs.edit();
537                            ed.putString("favorites", favorites.toString());
538                            ed.commit();
539                  }                  }
540          }          }
541  }  }

Legend:
Removed from v.258  
changed lines
  Added in v.1558

  ViewVC Help
Powered by ViewVC 1.1.20