/[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 237 by torben, Sat Aug 8 19:02:20 2009 UTC android/TrainInfo/src/dk/thoerup/traininfo/StationList.java revision 481 by torben, Thu Oct 29 08:56:17 2009 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfo;  package dk.thoerup.traininfo;
2    
3    import java.util.ArrayList;
4    import java.util.List;
5    import java.util.Locale;
6    
7  import android.app.AlertDialog;  import android.app.AlertDialog;
8  import android.app.Dialog;  import android.app.Dialog;
9  import android.app.ListActivity;  import android.app.ListActivity;
10  import android.app.ProgressDialog;  import android.app.ProgressDialog;
11  import android.content.DialogInterface;  import android.content.DialogInterface;
12  import android.content.Intent;  import android.content.Intent;
13    import android.content.SharedPreferences;
14    import android.content.SharedPreferences.Editor;
15    import android.location.Address;
16    import android.location.Geocoder;
17    import android.location.Location;
18    import android.os.AsyncTask;
19  import android.os.Bundle;  import android.os.Bundle;
20  import android.os.Handler;  import android.os.Handler;
21  import android.os.Message;  import android.os.Message;
22    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;
35    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;
40    
41    public class StationList extends ListActivity  {
42            public static final int GOTLOCATION = 1001;
43            public static final int GOTSTATIONLIST = 1002;
44            public static final int NOPROVIDER = 1003;
45            public static final int LOCATIONFIXTIMEOUT = 1004;
46            
47            public static final int OPTIONS_MAP = 2003;
48            public static final int OPTIONS_GPSINFO = 2004;
49    
50            
51    
 public class TrainInfoList extends ListActivity  {  
         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;  
52                    
53          public static final int DLG_PROGRESS = 1;          public static final int DLG_PROGRESS = 3001;
54            public static final int DLG_STATIONNAME = 3002;
55            
56            static enum LookupMethod {
57                    ByLocation,
58                    ByName,
59                    ByList,
60                    MethodNone
61            }
62                    
63          /** Called when the activity is first created. */          
64            String dialogMessage = "";
65          ProgressDialog dialog;          ProgressDialog dialog;
66          StationLocator locator = null;          LocationLookup locator = null;
67            FindStationsTask findStationsTask;
68            StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
69                    
70          boolean isRunning;          GeoPair location = new GeoPair();
71            
72            boolean isRunning = false;
73            List<StationBean> stations = new ArrayList<StationBean>();
74            
75            StationProvider stationProvider = ProviderFactory.getStationProvider();
76                    
77          StationListAdapter adapter = null;          StationListAdapter adapter = null;
78            
79            FavoritesMenu contextMenu = new FavoritesMenu();
80            IntSet favorites = new IntSet();
81    
82            WelcomeScreen.ListType listType;
83            String dialogTitle;
84            SharedPreferences prefs;
85            
86            ///////////////////////////////////////////////////////////////////////////////////////////
87            //Activity call backs
88            
89            @SuppressWarnings("unchecked")
90          @Override          @Override
91          public void onCreate(Bundle savedInstanceState) {          public void onCreate(Bundle savedInstanceState) {
92                  super.onCreate(savedInstanceState);                  super.onCreate(savedInstanceState);
93                  setContentView(R.layout.main);                  setContentView(R.layout.stationlist);
94                    
95                                    
96                  adapter = new StationListAdapter(this);                  adapter = new StationListAdapter(this);
97                  setListAdapter(adapter);                  setListAdapter(adapter);
98                                    
99                  locator = new StationLocator(this, stationsFetched);                  ListView lv = getListView();
100                    lv.setOnCreateContextMenuListener(contextMenu);
101                    
102                    locator = new LocationLookup(this, stationsFetched);
103                                    
104                  startLookup();  
105                    prefs = getSharedPreferences("TrainStation", 0);
106                    String favoriteString = prefs.getString("favorites", "");
107                    if (! favoriteString.equals("") ) {
108                            favorites.fromString(favoriteString);
109                    }
110                    
111                    if (savedInstanceState == null) {
112                            listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type");
113                            switch (listType) {
114                            case ListNearest:
115                                    startLookup();
116                                    break;
117                            case ListSearch:
118                                    this.showDialog(DLG_STATIONNAME);
119                                    break;
120                            case ListFavorites:
121                                    startFavoriteLookup();
122                                    break;
123                            default:
124                                    // Not possible !?!
125                            }
126                            
127                    } else {
128                            stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");
129                            adapter.setStations(stations);
130                            location = (GeoPair) savedInstanceState.getSerializable("location");
131                            dialogTitle = savedInstanceState.getString("title");
132                            setTitle(dialogTitle);
133                    }
134          }          }
135    
136    
137        @Override
138        public void onSaveInstanceState(Bundle outState)
139        {
140            if (dialog != null && dialog.isShowing())
141                    dialog.dismiss();
142            outState.putSerializable("stations", (ArrayList<StationBean>) stations);
143            outState.putSerializable("location", location);
144            outState.putString("title", dialogTitle);
145        }
146                    
147                    
148    
149          @Override          @Override
150            public boolean onCreateOptionsMenu(Menu menu) {
151                    MenuItem item;
152                                    
153                    item = menu.add(0, OPTIONS_MAP, 0, "Station map");
154                    item.setIcon(android.R.drawable.ic_menu_mapmode);
155                    
156                    item = menu.add(0, OPTIONS_GPSINFO, 0, "GPS Info");
157                    item.setIcon(android.R.drawable.ic_menu_mapmode);              
158                    
159                    return true;
160            }
161    
162            @Override
163            public boolean onOptionsItemSelected(MenuItem item) {
164                    boolean retval = true;
165    
166                    //TODO: Cleanup
167                    switch (item.getItemId()) {
168                    case OPTIONS_MAP:
169                            
170                            Intent intent = new Intent(this,StationMapView.class);
171                            intent.putExtra("userlocation", location );
172                            
173                            ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
174                            for (StationBean st : stations ) {
175                                    stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
176                            }
177                            
178                            intent.putExtra("stations", stationPoints);
179                            
180                            startActivity(intent);
181                            break;
182                    case OPTIONS_GPSINFO:
183                            Location loc = locator.getLocation();
184                            StringBuffer message = new StringBuffer();
185                            message.append("Location info:\n");
186                            message.append("-Obtained by: ").append(loc != null ? loc.getProvider() : "-").append("\n");
187                            message.append("-Accuracy: ").append(loc != null ? (int)loc.getAccuracy() : "-").append("m\n");
188    
189                            MessageBox.showMessage(this, message.toString());
190                            break;
191                    default:
192                            retval = super.onOptionsItemSelected(item);
193                    }
194                    
195                    return retval;
196            }
197            
198            
199    
200            @Override
201            public boolean onContextItemSelected(MenuItem item) {
202                    contextMenu.onContextItemSelected(item);
203                    return true;
204    
205    
206            }
207    
208    
209    
210    
211            @Override
212          protected Dialog onCreateDialog(int id) {          protected Dialog onCreateDialog(int id) {
213                  switch (id) {                  switch (id) {
214                  case DLG_PROGRESS:                  case DLG_PROGRESS:
215                          ProgressDialog dlg = new ProgressDialog(this);                          ProgressDialog dlg = new ProgressDialog(this);
216                          dlg.setMessage("Wait for location fix");                          dlg.setMessage("Wait for location fix");
217                          dlg.setCancelable(false);                          dlg.setCancelable(false);
218                          return dlg;                          return dlg;                    
219                    case DLG_STATIONNAME:
220                            LayoutInflater factory = LayoutInflater.from(this);
221                            final View rootView = factory.inflate(R.layout.textinput, null);
222                            
223                            
224                            AlertDialog.Builder builder = new AlertDialog.Builder(this);
225                            
226                            builder.setTitle("Station search");
227                            builder.setView(rootView);
228                            builder.setCancelable(true);
229                            builder.setPositiveButton("Search", new DialogInterface.OnClickListener() {
230                                    public void onClick(DialogInterface dialog, int which) {
231                                            EditText et = (EditText) rootView.findViewById(R.id.EditText);
232                                            dialog.dismiss();
233                                            if (et.getText().toString().length() >= 2) {
234                                                    startNameSearch(et.getText().toString());
235                                            } else {
236                                                    MessageBox.showMessage(StationList.this, "Two characters minimum" );
237                                            }
238                                    }
239                            });
240                            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
241                                    public void onClick(DialogInterface dialog, int which) {
242                                            dialog.dismiss();
243                                    }
244                            });                    
245                            return builder.create();
246                            
247                  default:                  default:
248                          return super.onCreateDialog(id);                                          return super.onCreateDialog(id);                
249                  }                  }
# Line 58  public class TrainInfoList extends ListA Line 251  public class TrainInfoList extends ListA
251          }          }
252                    
253                    
   
   
254          @Override          @Override
255          protected void onPrepareDialog(int id, Dialog dialog) {          protected void onPrepareDialog(int id, Dialog dialog) {
256                  super.onPrepareDialog(id, dialog);                  super.onPrepareDialog(id, dialog);
257                  switch (id) {                  switch (id) {
258                  case DLG_PROGRESS:                  case DLG_PROGRESS:
259                          this.dialog = (ProgressDialog) dialog;                          this.dialog = (ProgressDialog) dialog;
260                            if (!dialogMessage.equals("")) {
261                                    this.dialog.setMessage(dialogMessage);
262                                    dialogMessage = "";
263                            }
264                          break;                          break;
265                  }                  }
266          }          }
267            
268            @Override
269            protected void onListItemClick(ListView l, View v, int position, long id) {
270                    super.onListItemClick(l, v, position, id);
271                                    
272                    StationBean station = stations.get(position);
273    
274                    double latitude = station.getLatitude();
275                    double longitude = station.getLongitude();
276    
277    
278          public void progressDialog() {                  
279                  dialog = new ProgressDialog(this);                  Intent intent = new Intent(this, DepartureList.class);
280                  dialog.setMessage("Wait for location fix");                  intent.putExtra("name", station.getName());
281                  dialog.setCancelable(false);                  intent.putExtra("distance", station.getDistance());
282                  dialog.show();                  intent.putExtra("latitude", latitude);
283                    intent.putExtra("longitude", longitude);
284                    intent.putExtra("stationid", station.getId());
285                    intent.putExtra("address", station.getAddress());
286                    startActivity(intent);
287          }          }
288    
289            /////////////////////////////////////////////////////////////
290            //
291    
292          public void startLookup() {          public void startLookup() {
293                  isRunning = true;                  isRunning = true;
294                    dialogMessage = "Wait for location fix";
295                  showDialog(DLG_PROGRESS);                  showDialog(DLG_PROGRESS);
                 //progressDialog();  
296                                    
297                  locator.locateStations();                  locator.locateStations();
298                  stationsFetched.sendEmptyMessageDelayed(FIXTIMEOUT, 20000);                              stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000);
299            }
300            
301            void startNameSearch(String name) {
302                    dialogMessage = "Finding stations by name";
303                    showDialog(DLG_PROGRESS);
304    
305                    findStationsTask = new FindStationsTask();
306                    findStationsTask.searchByName(name, locator.getLocation());
307                    findStationsTask.execute();
308                    
309            }
310            
311            public void startFavoriteLookup() {
312                    
313                    if (favorites.size() > 0) {
314                            dialogMessage = "Loading favorites";
315                            showDialog(DLG_PROGRESS);
316    
317                            findStationsTask = new FindStationsTask();
318                            findStationsTask.searchByIds(favorites.toString(), locator.getLocation());
319                            findStationsTask.execute();
320                    } else {
321                            MessageBox.showMessage(this, "Favorite list is empty");
322                    }
323          }          }
324    
325    
326          Handler stationsFetched = new Handler() {          
327            void startLocatorTask()
328            {
329                    dialogMessage = "Finding nearby stations";
330                    showDialog(DLG_PROGRESS);
331                    
332                    findStationsTask = new FindStationsTask();
333                    findStationsTask.searchByLocation( locator.getLocation() );
334                    findStationsTask.execute();    
335            }
336            
337    
338            String lookupAddress(double latitude, double longitude) {
339                    
340                    Geocoder coder = new Geocoder(this, new Locale("da"));
341                    StringBuilder sb = new StringBuilder();
342                    Log.i("lookupaddr", "" + latitude + "/" + longitude);
343                    try {
344                            List<Address> addressList = coder.getFromLocation(latitude, longitude, 1);
345                            Address addr = addressList.get(0);
346                            
347                            
348                            int max = addr.getMaxAddressLineIndex();
349                            for (int i=0; i<max; i++) {
350                                    if (i>0)
351                                            sb.append(", ");
352                                    
353                                    sb.append(addr.getAddressLine(i));
354                            }
355                            
356                            
357                    } catch (Exception e) {
358                            Log.e("DepartureList", "geocoder failed", e);
359                    }
360                    
361                    return sb.toString();
362            }
363            
364            
365            ////////////////////////////////////////////////////////////////////////////
366            // Inner classes
367    
368            class StationsFetchedHandler extends Handler {
369                  @Override                  @Override
370                  public void handleMessage(Message msg) {                  public void handleMessage(Message msg) {
371                            
372                          switch (msg.what) {                          switch (msg.what) {
373                          case GOTLOCATION:                          case GOTLOCATION:
374                                  dialog.setMessage("Finding nearby stations");                                  dismissDialog(DLG_PROGRESS);
375                                  break;                                  
376                          case GOTSTATIONLIST:                                  startLocatorTask();
377                                  dialog.dismiss();                                  location = GeoPair.fromLocation( locator.getLocation() );
378                                  adapter.setStations( locator.getStations() );                                  
379                                  break;                                  break;
380    
381                          case NOPROVIDER:                          case NOPROVIDER:
382                                  dialog.dismiss();                                  dismissDialog(DLG_PROGRESS);
383                                  showMessageBox("No Location provider enabled. Plase enabled gps.");                                  MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps.");
384                                  break;                                  break;
385                          case FIXTIMEOUT:                          case LOCATIONFIXTIMEOUT:                                
                                 dialog.dismiss();  
386                                  if (isRunning) {                                  if (isRunning) {
387                                          locator.abortLocationListener();                                          locator.stopSearch();
388                                          showMessageBox("GPS fix timed out");                                          if (locator.hasLocation()) {
389                                                    stationsFetched.sendEmptyMessage( GOTLOCATION );
390                                            } else {                                                
391                                                    dismissDialog(DLG_PROGRESS);
392                                                    
393                                                    AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                
394                                                    builder.setMessage("Location fix timed out");
395                                                    builder.setCancelable(true);
396                                                    builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
397                                                            public void onClick(DialogInterface dialog, int id) {
398                                                                    dialog.dismiss();
399                                                                    startLookup();
400                                                                    
401                                                            }
402                                                    });
403                                                    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
404                                                            public void onClick(DialogInterface dialog, int id) {
405                                                                    dialog.dismiss();
406                                                            }                                                      
407                                                    });                                                                                            
408                                                    builder.show();
409    
410                                            }
411                                  }                                  }
412                                  break;                                  break;
                         case LOOKUPSTATIONFAILED:  
                                 dialog.dismiss();  
                                 showMessageBox("Error on finding nearby stations");  
                                 break;  
413                          }                          }
                           
414                          isRunning = false;                          isRunning = false;
415                  }                  }
416          };          };
417    
418                    
419                    class FindStationsTask extends AsyncTask<Void,Void,Void> {
           
         @Override  
         protected void onListItemClick(ListView l, View v, int position, long id) {  
                 super.onListItemClick(l, v, position, id);  
420                                    
421                  StationBean station = adapter.getStation(position);                  LookupMethod method = LookupMethod.MethodNone;
422                    boolean success;
423                    String name;
424                    Location loc;
425                    String ids;
426                                    
427                    public void searchByName(String n, Location l) {
428                            
429                            method = LookupMethod.ByName;
430                            loc = l;
431                            name = n;
432                    }
433                                    
434                  Intent intent = new Intent(this, DepartureList.class);                  public void searchByLocation(Location l) {
435                  intent.putExtra("name", station.getName());                          method = LookupMethod.ByLocation;
436                  intent.putExtra("address", station.getAddress());                          loc = l;
437                  intent.putExtra("distance", station.getDistance());                  }
438                  startActivity(intent);                  
439          }                  public void searchByIds(String id, Location l) {
440                            
441                            method = LookupMethod.ByList;
442                            loc = l;
443                            ids = id;
444                    }
445                    
446                    @Override
447                    protected void onPreExecute() {
448    
449          public void showMessageBox(String message) {                          if (method.equals(LookupMethod.MethodNone))
450                  AlertDialog.Builder builder = new AlertDialog.Builder(this);                                  throw new RuntimeException("Method not set");
451                  builder.setMessage(message)                          super.onPreExecute();
452                  .setCancelable(false)                  }
453                  .setPositiveButton("OK", new DialogInterface.OnClickListener() {                  
454                          public void onClick(DialogInterface dialog, int id) {                  @Override
455                                  dialog.dismiss();                  protected Void doInBackground(Void... params) {
456    
457                            switch (method) {
458                            case ByLocation:
459                                    success = stationProvider.lookupStations(loc);
460                                    break;
461                            case ByName:
462                                    success = stationProvider.lookupStationsByName(name);
463                                    break;
464                            case ByList:
465                                    success = stationProvider.lookupStationsByIds(ids);
466                                    break;
467                            default:
468                                    success = false; // not possible        
469                          }                          }
470                  })                          
471                  .show();                          
472                            Location dummy = new Location("gps");
473                            List<StationBean> stations = stationProvider.getStations();
474                            
475                            for (StationBean station : stations) {
476                                    String addr = lookupAddress(station.getLatitude(), station.getLongitude());
477                                    station.setAddress(addr);
478                                    
479                                    
480                                    if (method.equals(LookupMethod.ByName) || method.equals(LookupMethod.ByList)) {
481                                            if (loc != null) { //only do the distance calc if we have a location
482                                                    dummy.setLatitude(station.getLatitude());
483                                                    dummy.setLongitude(station.getLongitude());
484                                                    station.setDistance( (int)loc.distanceTo(dummy) );
485                                            } else {
486                                                    station.setDistance(0);
487                                            }
488                                    }
489    
490                            }                                              
491                            
492                            return null;
493                    }
494    
495                    @Override
496                    protected void onPostExecute(Void result) {
497                            super.onPostExecute(result);
498                            dialog.dismiss();
499                            
500                            //set title
501                            switch (method) {
502                            case ByLocation:
503                                    dialogTitle = "Traininfo DK - Nearby stations";
504                                    break;
505                            case ByName:
506                                    dialogTitle = "Traininfo DK - Search";
507                                    break;
508                            case ByList:
509                                    dialogTitle = "Traininfo DK - Favorites";
510                                    break;
511                            default:
512                                    dialogTitle = "";//not possible                                
513                            }                              
514                            
515                            StationList.this.setTitle(dialogTitle);
516                            //set title end
517                            
518                            if (success) {                          
519                                    if (stationProvider.getStations().size() == 0)
520                                            MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?!
521                                    stations = stationProvider.getStations();
522                                    adapter.setStations( stations );                                
523                                    
524                            } else { //communication or parse errors
525                                    AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                
526                                    builder.setMessage("Error on finding nearby stations");
527                                    builder.setCancelable(true);
528                                    builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
529                                            public void onClick(DialogInterface dialog, int id) {
530                                                    dialog.dismiss();
531                                                    
532                                                    stationsFetched.post( new Runnable() {
533                                                            @Override
534                                                            public void run() {
535                                                                    startLocatorTask();                                                            
536                                                            }
537                                                    });
538                                            }
539                                    });
540                                    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
541                                            public void onClick(DialogInterface dialog, int id) {
542                                                    dialog.dismiss();
543                                            }                                                      
544                                    });                                                                                            
545                                    builder.show();                        
546                            }
547                    }
548            }
549            
550            
551            class FavoritesMenu implements OnCreateContextMenuListener {
552                    private final static int FAVORITES_ADD = 9001;
553                    private final static int FAVORITES_REMOVE = 9002;
554                    
555                    private int selectedPosition;
556                    
557                    
558                    @Override
559                    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
560                                                    
561                            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
562                            selectedPosition = info.position;
563                            int stationID = stations.get(selectedPosition).getId();
564    
565                            if (!favorites.contains(stationID)) {
566                                    menu.add(0, FAVORITES_ADD, 0, "Add to favorites");
567                            } else {
568                                    menu.add(0, FAVORITES_REMOVE, 0, "Remove from favorites");
569                            }
570                            
571                    }
572                    
573                    public void onContextItemSelected(MenuItem item) {
574                            StationBean sb = stations.get(selectedPosition);
575                            
576                            int stationID = sb.getId();
577                            if (item.getItemId() == FAVORITES_ADD) {
578                                    favorites.add(stationID);
579                                    Toast.makeText(StationList.this, "Station added", Toast.LENGTH_SHORT).show();
580                            } else {
581                                    
582                                    favorites.remove(stationID);
583                                    Toast.makeText(StationList.this, "Station removed", Toast.LENGTH_SHORT).show();
584                                    
585                                    
586                                    if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) {
587                                            stations.remove(selectedPosition);
588                                            adapter.notifyDataSetChanged();
589                                    }
590                            }
591                            Editor ed = prefs.edit();
592                            ed.putString("favorites", favorites.toString());
593                            ed.commit();
594                    }
595          }          }
596  }  }

Legend:
Removed from v.237  
changed lines
  Added in v.481

  ViewVC Help
Powered by ViewVC 1.1.20