/[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 319 by torben, Fri Sep 11 12:24:53 2009 UTC android/TrainInfo/src/dk/thoerup/traininfo/StationList.java revision 420 by torben, Thu Oct 8 11:50:46 2009 UTC
# Line 4  import java.util.ArrayList; Line 4  import java.util.ArrayList;
4  import java.util.List;  import java.util.List;
5  import java.util.Locale;  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;  import android.location.Address;
14  import android.location.Geocoder;  import android.location.Geocoder;
# Line 16  import android.os.Bundle; Line 18  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;  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;  import dk.thoerup.traininfo.provider.ProviderFactory;
28  import dk.thoerup.traininfo.provider.StationProvider;  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          LocationLookup 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();          StationProvider stationProvider = ProviderFactory.getStationProvider();
61                    
62            StationListAdapter adapter = null;
63                    
64            static enum LookupMethod {
65                    ByLocation,
66                    ByName,
67                    MethodNone
68            }
69            
70            ///////////////////////////////////////////////////////////////////////////////////////////
71            //Activity call backs
72                    
         StationListAdapter adapter = null;  
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                                    
                 LocationLookup.removeMockLocation(this);  
                 //StationLocator.injectMockLocation(this);  
79                                    
80                  adapter = new StationListAdapter(this);                  adapter = new StationListAdapter(this);
81                  setListAdapter(adapter);                  setListAdapter(adapter);
# Line 61  public class TrainInfoList extends ListA Line 86  public class TrainInfoList extends ListA
86                  } else {                  } else {
87                          stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");                          stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");
88                          adapter.setStations(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                    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 89  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          }          }
   
         public void startLookup() {  
                 isRunning = true;  
                 showDialog(DLG_PROGRESS);  
                   
                 locator.locateStations();  
                 stationsFetched.sendEmptyMessageDelayed(FIXTIMEOUT, 20000);  
         }  
   
   
         Handler stationsFetched = new Handler() {  
                 @Override  
                 public void handleMessage(Message msg) {  
                         switch (msg.what) {  
                         case GOTLOCATION:  
                                 dialog.setMessage("Finding nearby stations");  
                                 locatorTask.execute();  
                                 break;  
   
                         case NOPROVIDER:  
                                 dialog.dismiss();  
                                 MessageBox.showMessage(TrainInfoList.this,"No location provider enabled. Plase enable gps.");  
                                 break;  
                         case FIXTIMEOUT:  
                                 dialog.dismiss();  
                                 if (isRunning) {  
                                         locator.abortLocationListener();  
                                         if (locator.hasLocation()) {  
                                                 msg.what = GOTLOCATION;  
                                                 handleMessage( msg ); // ToDo: ugly recursive call !!!  
                                         } else {  
                                                 MessageBox.showMessage(TrainInfoList.this,"GPS fix timed out");  
                                         }  
                                 }  
                                 break;  
                         case LOOKUPSTATIONFAILED:  
                                 dialog.dismiss();  
                                 MessageBox.showMessage(TrainInfoList.this,"Error on finding nearby stations");  
                                 break;  
                         }  
                         isRunning = false;  
                 }  
         };  
           
           
226                    
227          @Override          @Override
228          protected void onListItemClick(ListView l, View v, int position, long id) {          protected void onListItemClick(ListView l, View v, int position, long id) {
# Line 166  public class TrainInfoList extends ListA Line 245  public class TrainInfoList extends ListA
245                  startActivity(intent);                  startActivity(intent);
246          }          }
247    
248            /////////////////////////////////////////////////////////////
249            //
250    
251            public void startLookup() {
252                    isRunning = true;
253                    dialogMessage = "Wait for location fix";
254                    showDialog(DLG_PROGRESS);
255                    
256                    locator.locateStations();
257                    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) {          String lookupAddress(double latitude, double longitude) {
284                                    
285                  Geocoder coder = new Geocoder(this, new Locale("da"));                  Geocoder coder = new Geocoder(this, new Locale("da"));
# Line 192  public class TrainInfoList extends ListA Line 306  public class TrainInfoList extends ListA
306                  return sb.toString();                  return sb.toString();
307          }          }
308                    
309            
310            ////////////////////////////////////////////////////////////////////////////
311            // Inner classes
312    
313            class StationsFetchedHandler extends Handler {
314                    @Override
315                    public void handleMessage(Message msg) {
316    
317                            switch (msg.what) {
318                            case GOTLOCATION:
319                                    dismissDialog(DLG_PROGRESS);
320                                    
321                                    startLocatorTask();
322                                    location = GeoPair.fromLocation( locator.getLocation() );
323                                    
324                                    break;
325    
326                            case NOPROVIDER:
327                                    dismissDialog(DLG_PROGRESS);
328                                    MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps.");
329                                    break;
330                            case LOCATIONFIXTIMEOUT:                                
331                                    if (isRunning) {
332                                            locator.stopSearch();
333                                            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("Location 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;
358                            }
359                            isRunning = false;
360                    }
361            };
362    
363            
364          class LocatorTask extends AsyncTask<Void,Void,Void> {          class LocatorTask extends AsyncTask<Void,Void,Void> {
365                    
366                    LookupMethod method = LookupMethod.MethodNone;
367                  boolean success;                  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                    public void searchByLocation(Location l) {
379                            method = LookupMethod.ByLocation;
380                            loc = l;
381                    }
382                    
383                  @Override                  @Override
384                  protected void onPreExecute() {                  protected void onPreExecute() {
385    
386                            if (method.equals(LookupMethod.MethodNone))
387                                    throw new RuntimeException("Method not set");
388                          super.onPreExecute();                          super.onPreExecute();
389                  }                  }
390                                    
391                  @Override                  @Override
392                  protected Void doInBackground(Void... params) {                  protected Void doInBackground(Void... params) {
393                          Location loc = locator.getLocation();                  
394                          success = stationProvider.lookupStations(loc);                          if (method.equals(LookupMethod.ByLocation))
395                                    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();                          List<StationBean> stations = stationProvider.getStations();
402                          for (StationBean station : stations) {                          
403                            for (StationBean station : stations) {
404                                  String addr = lookupAddress(station.getLatitude(), station.getLongitude());                                  String addr = lookupAddress(station.getLatitude(), station.getLongitude());
405                                  station.setAddress(addr);                                  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;                          return null;
415                  }                  }
# Line 222  public class TrainInfoList extends ListA Line 421  public class TrainInfoList extends ListA
421                                                    
422                          if (success) {                                                    if (success) {                          
423                                  if (stationProvider.getStations().size() == 0)                                  if (stationProvider.getStations().size() == 0)
424                                          MessageBox.showMessage(TrainInfoList.this, "No stations found!"); // this should not be possible !?!                                          MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?!
425                                  stations = stationProvider.getStations();                                  stations = stationProvider.getStations();
426                                  adapter.setStations( stations );                                                                  adapter.setStations( stations );                                
427                                                                    
428                          } else { //communication or parse errors                          } else { //communication or parse errors
429                                  MessageBox.showMessage(TrainInfoList.this, "Error finding stations!");                                  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          }          }

Legend:
Removed from v.319  
changed lines
  Added in v.420

  ViewVC Help
Powered by ViewVC 1.1.20