/[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 401 by torben, Tue Oct 6 19:13:34 2009 UTC
# Line 2  package dk.thoerup.traininfo; Line 2  package dk.thoerup.traininfo;
2    
3  import java.util.ArrayList;  import java.util.ArrayList;
4  import java.util.List;  import java.util.List;
5    import java.util.Locale;
6    
7    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;
12  import android.content.Intent;  import android.content.Intent;
13    import android.location.Address;
14    import android.location.Geocoder;
15    import android.location.Location;
16  import android.os.AsyncTask;  import android.os.AsyncTask;
17  import android.os.Bundle;  import android.os.Bundle;
18  import android.os.Handler;  import android.os.Handler;
19  import android.os.Message;  import android.os.Message;
20    import android.util.Log;
21    import android.view.LayoutInflater;
22    import android.view.Menu;
23    import android.view.MenuItem;
24  import android.view.View;  import android.view.View;
25    import android.widget.EditText;
26  import android.widget.ListView;  import android.widget.ListView;
27    import dk.thoerup.traininfo.provider.ProviderFactory;
28    import dk.thoerup.traininfo.provider.StationProvider;
29    import dk.thoerup.traininfo.stationmap.GeoPair;
30    import dk.thoerup.traininfo.stationmap.StationMapView;
31  import dk.thoerup.traininfo.util.MessageBox;  import dk.thoerup.traininfo.util.MessageBox;
32    
33  public class TrainInfoList extends ListActivity  {  public class StationList extends ListActivity  {
34          public static final int GOTLOCATION = 1;          public static final int GOTLOCATION = 1001;
35          public static final int GOTSTATIONLIST = 2;          public static final int GOTSTATIONLIST = 1002;
36          public static final int NOPROVIDER = 3;          public static final int NOPROVIDER = 1003;
37          public static final int FIXTIMEOUT = 4;          public static final int LOCATIONFIXTIMEOUT = 1004;
38          public static final int LOOKUPSTATIONFAILED = 5;          
39            public static final int OPTIONS_RESCAN = 2001;
40            public static final int OPTIONS_NAMESEARCH = 2002;
41            public static final int OPTIONS_MAP = 2003;
42            public static final int OPTIONS_ABOUT = 2004;
43    
44                    
45          public static final int DLG_PROGRESS = 1;          public static final int DLG_PROGRESS = 3001;
46            public static final int DLG_STATIONNAME = 3002;
47                    
48          /** Called when the activity is first created. */          /** Called when the activity is first created. */
49            String dialogMessage = "";
50          ProgressDialog dialog;          ProgressDialog dialog;
51          StationLocator locator = null;          LocationLookup locator = null;
52          LocatorTask locatorTask = new LocatorTask();          LocatorTask locatorTask;
53            StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
54            
55            GeoPair location = new GeoPair();
56                    
57          boolean isRunning = false;          boolean isRunning = false;
58          List<StationBean> stations = new ArrayList<StationBean>();          List<StationBean> stations = new ArrayList<StationBean>();
59                    
60                    StationProvider stationProvider = ProviderFactory.getStationProvider();
61                    
62          StationListAdapter adapter = null;          StationListAdapter adapter = null;
63            
64            static enum LookupMethod {
65                    ByLocation,
66                    ByName,
67                    MethodNone
68            }
69            
70            ///////////////////////////////////////////////////////////////////////////////////////////
71            //Activity call backs
72            
73          @SuppressWarnings("unchecked")          @SuppressWarnings("unchecked")
74          @Override          @Override
75          public void onCreate(Bundle savedInstanceState) {          public void onCreate(Bundle savedInstanceState) {
76                  super.onCreate(savedInstanceState);                  super.onCreate(savedInstanceState);
77                  setContentView(R.layout.main);                  setContentView(R.layout.main);
78                                    
                 StationLocator.removeMockLocation(this);  
                 //StationLocator.injectMockLocation(this);  
79                                    
80                  adapter = new StationListAdapter(this);                  adapter = new StationListAdapter(this);
81                  setListAdapter(adapter);                  setListAdapter(adapter);
82                                    
83                  locator = new StationLocator(this, stationsFetched);                  locator = new LocationLookup(this, stationsFetched);
84                  if (savedInstanceState == null) {                  if (savedInstanceState == null) {
85                          startLookup();                          startLookup();
86                  } else {                  } else {
87                          stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");                          stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");
88                          adapter.setStations(new ArrayList<StationBean>(stations));                          adapter.setStations(stations);
89                            location = (GeoPair) savedInstanceState.getSerializable("location");
90                  }                  }
91          }          }
92            
93    
94      @Override      @Override
95      public void onSaveInstanceState(Bundle outState)      public void onSaveInstanceState(Bundle outState)
96      {      {
97          if (dialog != null && dialog.isShowing())          if (dialog != null && dialog.isShowing())
98                  dialog.dismiss();                  dialog.dismiss();
99          outState.putSerializable("stations", (ArrayList<StationBean>) stations);          outState.putSerializable("stations", (ArrayList<StationBean>) stations);
100            outState.putSerializable("location", location);
101      }      }
102                    
103                    
104    
105          @Override          @Override
106            public boolean onCreateOptionsMenu(Menu menu) {
107                    menu.add(0, OPTIONS_RESCAN, 0, "Find nearest stations");
108                    menu.add(0, OPTIONS_NAMESEARCH, 0, "Search for station");
109                    menu.add(0, OPTIONS_MAP, 0, "Show station map");
110                    menu.add(0, OPTIONS_ABOUT, 0, "About");
111                    return true;
112            }
113    
114            @Override
115            public boolean onOptionsItemSelected(MenuItem item) {
116                    boolean retval = true;
117    
118                    
119                    switch (item.getItemId()) {
120                    case OPTIONS_RESCAN:
121                            startLookup();
122                            break;
123                    case OPTIONS_NAMESEARCH:
124                            showDialog(DLG_STATIONNAME);
125                            break;
126                    case OPTIONS_MAP:
127                            
128                            Intent intent = new Intent(this,StationMapView.class);
129                            intent.putExtra("userlocation", location );
130                            
131                            ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
132                            for (StationBean st : stations ) {
133                                    stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
134                            }
135                            
136                            intent.putExtra("stations", stationPoints);
137                            
138                            startActivity(intent);
139                            break;
140                    case OPTIONS_ABOUT:
141                            String ver = this.getResources().getString(R.string.app_version);
142                            
143                            Location loc = locator.getLocation();
144                            StringBuffer message = new StringBuffer();
145                            message.append("TrainInfo DK v").append(ver).append("\n");
146                            message.append("By Torben Nielsen\n");
147                            message.append("\n");
148                            message.append("Location info:\n");
149                            message.append("-Obtained by: ").append(loc != null ? loc.getProvider() : "-").append("\n");
150                            message.append("-Accuracy: ").append(loc != null ? (int)loc.getAccuracy() : "-").append("m\n");
151    
152                            MessageBox.showMessage(this, message.toString());
153                            break;
154                    default:
155                            retval = super.onOptionsItemSelected(item);
156                    }
157                    
158                    return retval;
159            }
160    
161            @Override
162          protected Dialog onCreateDialog(int id) {          protected Dialog onCreateDialog(int id) {
163                  switch (id) {                  switch (id) {
164                  case DLG_PROGRESS:                  case DLG_PROGRESS:
165                          ProgressDialog dlg = new ProgressDialog(this);                          ProgressDialog dlg = new ProgressDialog(this);
166                          dlg.setMessage("Wait for location fix");                          dlg.setMessage("Wait for location fix");
167                          dlg.setCancelable(false);                          dlg.setCancelable(false);
168                          return dlg;                          return dlg;                    
169                    case DLG_STATIONNAME:
170                            LayoutInflater factory = LayoutInflater.from(this);
171                            final View rootView = factory.inflate(R.layout.textinput, null);
172                            
173                            
174                            AlertDialog.Builder builder = new AlertDialog.Builder(this);
175                            
176                            builder.setTitle("Station search");
177                            builder.setView(rootView);
178                            builder.setCancelable(true);
179                            builder.setPositiveButton("Search", new DialogInterface.OnClickListener() {
180                                    public void onClick(DialogInterface dialog, int which) {
181                                            EditText et = (EditText) rootView.findViewById(R.id.EditText);
182                                            dialog.dismiss();
183                                            if (et.getText().toString().length() >= 2) {
184                                                    startNameSearch(et.getText().toString());
185                                            } else {
186                                                    MessageBox.showMessage(StationList.this, "Two characters minimum" );
187                                            }
188                                    }
189                            });
190                            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
191                                    public void onClick(DialogInterface dialog, int which) {
192                                            dialog.dismiss();
193                                    }
194                            });                    
195                            return builder.create();
196                            
197                  default:                  default:
198                          return super.onCreateDialog(id);                                          return super.onCreateDialog(id);                
199                  }                  }
# Line 81  public class TrainInfoList extends ListA Line 201  public class TrainInfoList extends ListA
201          }          }
202                    
203                    
   
204          @Override          @Override
205          protected void onPrepareDialog(int id, Dialog dialog) {          protected void onPrepareDialog(int id, Dialog dialog) {
206                  super.onPrepareDialog(id, dialog);                  super.onPrepareDialog(id, dialog);
207                  switch (id) {                  switch (id) {
208                  case DLG_PROGRESS:                  case DLG_PROGRESS:
209                          this.dialog = (ProgressDialog) dialog;                          this.dialog = (ProgressDialog) dialog;
210                            if (!dialogMessage.equals("")) {
211                                    this.dialog.setMessage(dialogMessage);
212                                    dialogMessage = "";
213                            }
214                          break;                          break;
215                  }                  }
216          }          }
217            
218            @Override
219            protected void onListItemClick(ListView l, View v, int position, long id) {
220                    super.onListItemClick(l, v, position, id);
221                                    
222                    StationBean station = stations.get(position);
223    
224                    double latitude = station.getLatitude();
225                    double longitude = station.getLongitude();
226    
227    
228                    
229                    Intent intent = new Intent(this, DepartureList.class);
230                    intent.putExtra("name", station.getName());
231                    intent.putExtra("distance", station.getDistance());
232                    intent.putExtra("latitude", latitude);
233                    intent.putExtra("longitude", longitude);
234                    intent.putExtra("stationid", station.getId());
235                    intent.putExtra("address", station.getAddress());
236                    startActivity(intent);
237            }
238    
239            /////////////////////////////////////////////////////////////
240            //
241    
242          public void startLookup() {          public void startLookup() {
243                  isRunning = true;                  isRunning = true;
244                    dialogMessage = "Wait for location fix";
245                  showDialog(DLG_PROGRESS);                  showDialog(DLG_PROGRESS);
246                                    
247                  locator.locateStations();                  locator.locateStations();
248                  stationsFetched.sendEmptyMessageDelayed(FIXTIMEOUT, 20000);                  stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000);
249            }
250            
251            void startNameSearch(String name) {
252                    dialogMessage = "Finding stations by name";
253                    showDialog(DLG_PROGRESS);
254    
255                    locatorTask = new LocatorTask();
256                    locatorTask.searchByName(name, locator.getLocation());
257                    locatorTask.execute();
258                    
259          }          }
260    
261    
262          Handler stationsFetched = new Handler() {          
263            void startLocatorTask()
264            {
265                    dialogMessage = "Finding nearby stations";
266                    showDialog(DLG_PROGRESS);
267                    
268                    locatorTask = new LocatorTask();
269                    locatorTask.searchByLocation( locator.getLocation() );
270                    locatorTask.execute();  
271            }
272            
273    
274            String lookupAddress(double latitude, double longitude) {
275                    
276                    Geocoder coder = new Geocoder(this, new Locale("da"));
277                    StringBuilder sb = new StringBuilder();
278                    Log.i("lookupaddr", "" + latitude + "/" + longitude);
279                    try {
280                            List<Address> addressList = coder.getFromLocation(latitude, longitude, 1);
281                            Address addr = addressList.get(0);
282                            
283                            
284                            int max = addr.getMaxAddressLineIndex();
285                            for (int i=0; i<max; i++) {
286                                    if (i>0)
287                                            sb.append(", ");
288                                    
289                                    sb.append(addr.getAddressLine(i));
290                            }
291                            
292                            
293                    } catch (Exception e) {
294                            Log.e("DepartureList", "geocoder failed", e);
295                    }
296                    
297                    return sb.toString();
298            }
299            
300            
301            ////////////////////////////////////////////////////////////////////////////
302            // Inner classes
303    
304            class StationsFetchedHandler extends Handler {
305                  @Override                  @Override
306                  public void handleMessage(Message msg) {                  public void handleMessage(Message msg) {
307    
308                          switch (msg.what) {                          switch (msg.what) {
309                          case GOTLOCATION:                          case GOTLOCATION:
310                                  dialog.setMessage("Finding nearby stations");                                  dismissDialog(DLG_PROGRESS);
311                                  locatorTask.execute();                                  
312                                  break;                                  startLocatorTask();
313                          case GOTSTATIONLIST:                                  location = GeoPair.fromLocation( locator.getLocation() );
314                                  dialog.dismiss();                                  
                                 if (locator.getStations().size() == 0)  
                                         MessageBox.showMessage(TrainInfoList.this,"Error loading station list!");  
                                 stations = locator.getStations();  
                                 adapter.setStations( stations );  
315                                  break;                                  break;
316    
317                          case NOPROVIDER:                          case NOPROVIDER:
318                                  dialog.dismiss();                                  dismissDialog(DLG_PROGRESS);
319                                  MessageBox.showMessage(TrainInfoList.this,"No location provider enabled. Plase enable gps.");                                  MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps.");
320                                  break;                                  break;
321                          case FIXTIMEOUT:                          case LOCATIONFIXTIMEOUT:                                
                                 dialog.dismiss();  
322                                  if (isRunning) {                                  if (isRunning) {
323                                          locator.abortLocationListener();                                          locator.stopSearch();
324                                          MessageBox.showMessage(TrainInfoList.this,"GPS fix timed out");                                          if (locator.hasLocation()) {
325                                                    stationsFetched.sendEmptyMessage( GOTLOCATION );
326                                            } else {                                                
327                                                    dismissDialog(DLG_PROGRESS);
328                                                    
329                                                    AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                
330                                                    builder.setMessage("GPS fix timed out");
331                                                    builder.setCancelable(true);
332                                                    builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
333                                                            public void onClick(DialogInterface dialog, int id) {
334                                                                    dialog.dismiss();
335                                                                    startLookup();
336                                                                    
337                                                            }
338                                                    });
339                                                    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
340                                                            public void onClick(DialogInterface dialog, int id) {
341                                                                    dialog.dismiss();
342                                                            }                                                      
343                                                    });                                                                                            
344                                                    builder.show();
345    
346                                            }
347                                  }                                  }
348                                  break;                                  break;
                         case LOOKUPSTATIONFAILED:  
                                 dialog.dismiss();  
                                 MessageBox.showMessage(TrainInfoList.this,"Error on finding nearby stations");  
                                 break;  
349                          }                          }
350                          isRunning = false;                          isRunning = false;
351                  }                  }
352          };          };
353    
354                    
355                    class LocatorTask extends AsyncTask<Void,Void,Void> {
           
         @Override  
         protected void onListItemClick(ListView l, View v, int position, long id) {  
                 super.onListItemClick(l, v, position, id);  
356                                    
357                    LookupMethod method = LookupMethod.MethodNone;
358                    boolean success;
359                    String name;
360                    Location loc;
361                                    
362                  StationBean station = stations.get(position);                  public void searchByName(String n, Location l) {
363                            
364                            method = LookupMethod.ByName;
365                            loc = l;
366                            name = n;
367                    }
368                                    
369                    public void searchByLocation(Location l) {
370                            method = LookupMethod.ByLocation;
371                            loc = l;
372                    }
373                                    
                 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> {  
374                  @Override                  @Override
375                  protected void onPreExecute() {                  protected void onPreExecute() {
376    
377                            if (method.equals(LookupMethod.MethodNone))
378                                    throw new RuntimeException("Method not set");
379                          super.onPreExecute();                          super.onPreExecute();
380                  }                  }
381                                    
382                  @Override                  @Override
383                  protected Void doInBackground(Void... params) {                  protected Void doInBackground(Void... params) {
384                          locator.findNearestStations();                  
385                            if (method.equals(LookupMethod.ByLocation))
386                                    success = stationProvider.lookupStations(loc);
387                            
388                            if (method.equals(LookupMethod.ByName))
389                                    success = stationProvider.lookupStations(name);
390                            
391                            Location dummy = new Location("gps");
392                            List<StationBean> stations = stationProvider.getStations();
393                            
394                            for (StationBean station : stations) {
395                                    String addr = lookupAddress(station.getLatitude(), station.getLongitude());
396                                    station.setAddress(addr);
397                                    
398                                    if (method.equals(LookupMethod.ByName) ) {
399                                            dummy.setLatitude(station.getLatitude());
400                                            dummy.setLongitude(station.getLongitude());
401                                            station.setDistance( (int)loc.distanceTo(dummy) );
402                                    }
403                            }                                              
404                                                    
405                          return null;                          return null;
406                  }                  }
# Line 173  public class TrainInfoList extends ListA Line 408  public class TrainInfoList extends ListA
408                  @Override                  @Override
409                  protected void onPostExecute(Void result) {                  protected void onPostExecute(Void result) {
410                          super.onPostExecute(result);                          super.onPostExecute(result);
411                            dialog.dismiss();
412                            
413                            if (success) {                          
414                                    if (stationProvider.getStations().size() == 0)
415                                            MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?!
416                                    stations = stationProvider.getStations();
417                                    adapter.setStations( stations );                                
418                                    
419                            } else { //communication or parse errors
420                                    AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);                                                
421                                    builder.setMessage("Error on finding nearby stations");
422                                    builder.setCancelable(true);
423                                    builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
424                                            public void onClick(DialogInterface dialog, int id) {
425                                                    dialog.dismiss();
426                                                    
427                                                    stationsFetched.post( new Runnable() {
428                                                            @Override
429                                                            public void run() {
430                                                                    startLocatorTask();                                                            
431                                                            }
432                                                    });
433                                            }
434                                    });
435                                    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
436                                            public void onClick(DialogInterface dialog, int id) {
437                                                    dialog.dismiss();
438                                            }                                                      
439                                    });                                                                                            
440                                    builder.show();                        
441                            }
442                  }                  }
443          }          }
444  }  }

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

  ViewVC Help
Powered by ViewVC 1.1.20