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

Legend:
Removed from v.316  
changed lines
  Added in v.1709

  ViewVC Help
Powered by ViewVC 1.1.20