/[projects]/android/TrainInfo/src/dk/thoerup/traininfo/StationList.java
ViewVC logotype

Annotation of /android/TrainInfo/src/dk/thoerup/traininfo/StationList.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 401 - (hide annotations) (download)
Tue Oct 6 19:13:34 2009 UTC (14 years, 7 months ago) by torben
File size: 12254 byte(s)
Add location info to about box
1 torben 237 package dk.thoerup.traininfo;
2    
3 torben 258 import java.util.ArrayList;
4     import java.util.List;
5 torben 294 import java.util.Locale;
6 torben 258
7 torben 336 import android.app.AlertDialog;
8 torben 237 import android.app.Dialog;
9     import android.app.ListActivity;
10     import android.app.ProgressDialog;
11 torben 336 import android.content.DialogInterface;
12 torben 237 import android.content.Intent;
13 torben 294 import android.location.Address;
14     import android.location.Geocoder;
15 torben 319 import android.location.Location;
16 torben 241 import android.os.AsyncTask;
17 torben 237 import android.os.Bundle;
18     import android.os.Handler;
19     import android.os.Message;
20 torben 294 import android.util.Log;
21 torben 381 import android.view.LayoutInflater;
22 torben 368 import android.view.Menu;
23     import android.view.MenuItem;
24 torben 237 import android.view.View;
25 torben 381 import android.widget.EditText;
26 torben 237 import android.widget.ListView;
27 torben 319 import dk.thoerup.traininfo.provider.ProviderFactory;
28     import dk.thoerup.traininfo.provider.StationProvider;
29 torben 368 import dk.thoerup.traininfo.stationmap.GeoPair;
30     import dk.thoerup.traininfo.stationmap.StationMapView;
31 torben 245 import dk.thoerup.traininfo.util.MessageBox;
32 torben 237
33 torben 336 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 torben 368
39 torben 381 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 torben 336
44 torben 237
45 torben 381 public static final int DLG_PROGRESS = 3001;
46     public static final int DLG_STATIONNAME = 3002;
47 torben 237
48     /** Called when the activity is first created. */
49 torben 336 String dialogMessage = "";
50 torben 237 ProgressDialog dialog;
51 torben 319 LocationLookup locator = null;
52 torben 336 LocatorTask locatorTask;
53 torben 381 StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
54 torben 237
55 torben 374 GeoPair location = new GeoPair();
56    
57 torben 258 boolean isRunning = false;
58     List<StationBean> stations = new ArrayList<StationBean>();
59    
60 torben 319 StationProvider stationProvider = ProviderFactory.getStationProvider();
61 torben 381
62     StationListAdapter adapter = null;
63 torben 258
64 torben 381 static enum LookupMethod {
65     ByLocation,
66     ByName,
67     MethodNone
68     }
69 torben 319
70 torben 381 ///////////////////////////////////////////////////////////////////////////////////////////
71     //Activity call backs
72    
73 torben 258 @SuppressWarnings("unchecked")
74 torben 237 @Override
75     public void onCreate(Bundle savedInstanceState) {
76     super.onCreate(savedInstanceState);
77     setContentView(R.layout.main);
78    
79 torben 241
80 torben 237 adapter = new StationListAdapter(this);
81     setListAdapter(adapter);
82    
83 torben 319 locator = new LocationLookup(this, stationsFetched);
84 torben 258 if (savedInstanceState == null) {
85     startLookup();
86     } else {
87     stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");
88 torben 260 adapter.setStations(stations);
89 torben 374 location = (GeoPair) savedInstanceState.getSerializable("location");
90 torben 258 }
91 torben 237 }
92 torben 371
93    
94 torben 243 @Override
95     public void onSaveInstanceState(Bundle outState)
96     {
97 torben 258 if (dialog != null && dialog.isShowing())
98 torben 243 dialog.dismiss();
99 torben 258 outState.putSerializable("stations", (ArrayList<StationBean>) stations);
100 torben 374 outState.putSerializable("location", location);
101 torben 243 }
102 torben 237
103 torben 243
104 torben 237
105     @Override
106 torben 368 public boolean onCreateOptionsMenu(Menu menu) {
107 torben 381 menu.add(0, OPTIONS_RESCAN, 0, "Find nearest stations");
108     menu.add(0, OPTIONS_NAMESEARCH, 0, "Search for station");
109 torben 368 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 torben 381 boolean retval = true;
117    
118 torben 368
119     switch (item.getItemId()) {
120 torben 381 case OPTIONS_RESCAN:
121     startLookup();
122     break;
123     case OPTIONS_NAMESEARCH:
124     showDialog(DLG_STATIONNAME);
125     break;
126 torben 368 case OPTIONS_MAP:
127    
128     Intent intent = new Intent(this,StationMapView.class);
129 torben 374 intent.putExtra("userlocation", location );
130 torben 368
131     ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
132     for (StationBean st : stations ) {
133 torben 369 stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
134 torben 368 }
135    
136     intent.putExtra("stations", stationPoints);
137    
138     startActivity(intent);
139     break;
140 torben 371 case OPTIONS_ABOUT:
141     String ver = this.getResources().getString(R.string.app_version);
142    
143 torben 401 Location loc = locator.getLocation();
144 torben 371 StringBuffer message = new StringBuffer();
145     message.append("TrainInfo DK v").append(ver).append("\n");
146     message.append("By Torben Nielsen\n");
147 torben 401 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 torben 371
152     MessageBox.showMessage(this, message.toString());
153     break;
154 torben 368 default:
155     retval = super.onOptionsItemSelected(item);
156     }
157    
158     return retval;
159     }
160    
161     @Override
162 torben 237 protected Dialog onCreateDialog(int id) {
163     switch (id) {
164     case DLG_PROGRESS:
165     ProgressDialog dlg = new ProgressDialog(this);
166     dlg.setMessage("Wait for location fix");
167     dlg.setCancelable(false);
168 torben 336 return dlg;
169 torben 381 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 torben 382 MessageBox.showMessage(StationList.this, "Two characters minimum" );
187 torben 381 }
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 torben 237 default:
198     return super.onCreateDialog(id);
199     }
200    
201     }
202    
203    
204     @Override
205     protected void onPrepareDialog(int id, Dialog dialog) {
206     super.onPrepareDialog(id, dialog);
207     switch (id) {
208     case DLG_PROGRESS:
209     this.dialog = (ProgressDialog) dialog;
210 torben 336 if (!dialogMessage.equals("")) {
211     this.dialog.setMessage(dialogMessage);
212     dialogMessage = "";
213     }
214 torben 237 break;
215     }
216     }
217 torben 381
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 torben 237
224 torben 381 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 torben 237 public void startLookup() {
243     isRunning = true;
244 torben 381 dialogMessage = "Wait for location fix";
245 torben 237 showDialog(DLG_PROGRESS);
246    
247     locator.locateStations();
248 torben 336 stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000);
249 torben 237 }
250 torben 381
251     void startNameSearch(String name) {
252     dialogMessage = "Finding stations by name";
253     showDialog(DLG_PROGRESS);
254 torben 237
255 torben 381 locatorTask = new LocatorTask();
256     locatorTask.searchByName(name, locator.getLocation());
257     locatorTask.execute();
258    
259     }
260 torben 237
261 torben 381
262    
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 torben 237 @Override
306     public void handleMessage(Message msg) {
307 torben 336
308 torben 237 switch (msg.what) {
309     case GOTLOCATION:
310 torben 336 dismissDialog(DLG_PROGRESS);
311    
312     startLocatorTask();
313 torben 374 location = GeoPair.fromLocation( locator.getLocation() );
314 torben 336
315 torben 237 break;
316 torben 319
317 torben 237 case NOPROVIDER:
318 torben 336 dismissDialog(DLG_PROGRESS);
319     MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps.");
320 torben 237 break;
321 torben 336 case LOCATIONFIXTIMEOUT:
322 torben 237 if (isRunning) {
323 torben 336 locator.stopSearch();
324 torben 285 if (locator.hasLocation()) {
325 torben 336 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 torben 285 }
347 torben 237 }
348     break;
349     }
350     isRunning = false;
351     }
352     };
353 torben 381
354 torben 237
355 torben 381 class LocatorTask extends AsyncTask<Void,Void,Void> {
356 torben 336
357 torben 381 LookupMethod method = LookupMethod.MethodNone;
358     boolean success;
359     String name;
360     Location loc;
361 torben 237
362 torben 381 public void searchByName(String n, Location l) {
363 torben 317
364 torben 381 method = LookupMethod.ByName;
365     loc = l;
366     name = n;
367 torben 317 }
368    
369 torben 381 public void searchByLocation(Location l) {
370     method = LookupMethod.ByLocation;
371     loc = l;
372     }
373    
374 torben 241 @Override
375     protected void onPreExecute() {
376 torben 258
377 torben 381 if (method.equals(LookupMethod.MethodNone))
378     throw new RuntimeException("Method not set");
379 torben 241 super.onPreExecute();
380     }
381    
382     @Override
383     protected Void doInBackground(Void... params) {
384 torben 381
385     if (method.equals(LookupMethod.ByLocation))
386     success = stationProvider.lookupStations(loc);
387 torben 258
388 torben 381 if (method.equals(LookupMethod.ByName))
389     success = stationProvider.lookupStations(name);
390 torben 319
391 torben 381 Location dummy = new Location("gps");
392 torben 319 List<StationBean> stations = stationProvider.getStations();
393 torben 381
394     for (StationBean station : stations) {
395 torben 317 String addr = lookupAddress(station.getLatitude(), station.getLongitude());
396     station.setAddress(addr);
397 torben 381
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 torben 317
405 torben 241 return null;
406     }
407    
408     @Override
409     protected void onPostExecute(Void result) {
410     super.onPostExecute(result);
411 torben 319 dialog.dismiss();
412    
413     if (success) {
414     if (stationProvider.getStations().size() == 0)
415 torben 336 MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?!
416 torben 319 stations = stationProvider.getStations();
417     adapter.setStations( stations );
418    
419     } else { //communication or parse errors
420 torben 336 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 torben 319 }
442 torben 241 }
443     }
444 torben 237 }

  ViewVC Help
Powered by ViewVC 1.1.20