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

Legend:
Removed from v.240  
changed lines
  Added in v.419

  ViewVC Help
Powered by ViewVC 1.1.20