/[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 419 - (hide annotations) (download)
Thu Oct 8 07:31:37 2009 UTC (14 years, 7 months ago) by torben
File size: 12526 byte(s)
Use default android menu icons
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 419 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 torben 368 return true;
121     }
122    
123     @Override
124     public boolean onOptionsItemSelected(MenuItem item) {
125 torben 381 boolean retval = true;
126    
127 torben 368
128     switch (item.getItemId()) {
129 torben 381 case OPTIONS_RESCAN:
130     startLookup();
131     break;
132     case OPTIONS_NAMESEARCH:
133     showDialog(DLG_STATIONNAME);
134     break;
135 torben 368 case OPTIONS_MAP:
136    
137     Intent intent = new Intent(this,StationMapView.class);
138 torben 374 intent.putExtra("userlocation", location );
139 torben 368
140     ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
141     for (StationBean st : stations ) {
142 torben 369 stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
143 torben 368 }
144    
145     intent.putExtra("stations", stationPoints);
146    
147     startActivity(intent);
148     break;
149 torben 371 case OPTIONS_ABOUT:
150     String ver = this.getResources().getString(R.string.app_version);
151    
152 torben 401 Location loc = locator.getLocation();
153 torben 371 StringBuffer message = new StringBuffer();
154     message.append("TrainInfo DK v").append(ver).append("\n");
155     message.append("By Torben Nielsen\n");
156 torben 401 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 torben 371
161     MessageBox.showMessage(this, message.toString());
162     break;
163 torben 368 default:
164     retval = super.onOptionsItemSelected(item);
165     }
166    
167     return retval;
168     }
169    
170     @Override
171 torben 237 protected Dialog onCreateDialog(int id) {
172     switch (id) {
173     case DLG_PROGRESS:
174     ProgressDialog dlg = new ProgressDialog(this);
175     dlg.setMessage("Wait for location fix");
176     dlg.setCancelable(false);
177 torben 336 return dlg;
178 torben 381 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 torben 382 MessageBox.showMessage(StationList.this, "Two characters minimum" );
196 torben 381 }
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 torben 237 default:
207     return super.onCreateDialog(id);
208     }
209    
210     }
211    
212    
213     @Override
214     protected void onPrepareDialog(int id, Dialog dialog) {
215     super.onPrepareDialog(id, dialog);
216     switch (id) {
217     case DLG_PROGRESS:
218     this.dialog = (ProgressDialog) dialog;
219 torben 336 if (!dialogMessage.equals("")) {
220     this.dialog.setMessage(dialogMessage);
221     dialogMessage = "";
222     }
223 torben 237 break;
224     }
225     }
226 torben 381
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 torben 237
233 torben 381 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 torben 237 public void startLookup() {
252     isRunning = true;
253 torben 381 dialogMessage = "Wait for location fix";
254 torben 237 showDialog(DLG_PROGRESS);
255    
256     locator.locateStations();
257 torben 336 stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, 20000);
258 torben 237 }
259 torben 381
260     void startNameSearch(String name) {
261     dialogMessage = "Finding stations by name";
262     showDialog(DLG_PROGRESS);
263 torben 237
264 torben 381 locatorTask = new LocatorTask();
265     locatorTask.searchByName(name, locator.getLocation());
266     locatorTask.execute();
267    
268     }
269 torben 237
270 torben 381
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     class StationsFetchedHandler extends Handler {
314 torben 237 @Override
315     public void handleMessage(Message msg) {
316 torben 336
317 torben 237 switch (msg.what) {
318     case GOTLOCATION:
319 torben 336 dismissDialog(DLG_PROGRESS);
320    
321     startLocatorTask();
322 torben 374 location = GeoPair.fromLocation( locator.getLocation() );
323 torben 336
324 torben 237 break;
325 torben 319
326 torben 237 case NOPROVIDER:
327 torben 336 dismissDialog(DLG_PROGRESS);
328     MessageBox.showMessage(StationList.this,"No location provider enabled. Plase enable gps.");
329 torben 237 break;
330 torben 336 case LOCATIONFIXTIMEOUT:
331 torben 237 if (isRunning) {
332 torben 336 locator.stopSearch();
333 torben 285 if (locator.hasLocation()) {
334 torben 336 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 torben 285 }
356 torben 237 }
357     break;
358     }
359     isRunning = false;
360     }
361     };
362 torben 381
363 torben 237
364 torben 381 class LocatorTask extends AsyncTask<Void,Void,Void> {
365 torben 336
366 torben 381 LookupMethod method = LookupMethod.MethodNone;
367     boolean success;
368     String name;
369     Location loc;
370 torben 237
371 torben 381 public void searchByName(String n, Location l) {
372 torben 317
373 torben 381 method = LookupMethod.ByName;
374     loc = l;
375     name = n;
376 torben 317 }
377    
378 torben 381 public void searchByLocation(Location l) {
379     method = LookupMethod.ByLocation;
380     loc = l;
381     }
382    
383 torben 241 @Override
384     protected void onPreExecute() {
385 torben 258
386 torben 381 if (method.equals(LookupMethod.MethodNone))
387     throw new RuntimeException("Method not set");
388 torben 241 super.onPreExecute();
389     }
390    
391     @Override
392     protected Void doInBackground(Void... params) {
393 torben 381
394     if (method.equals(LookupMethod.ByLocation))
395     success = stationProvider.lookupStations(loc);
396 torben 258
397 torben 381 if (method.equals(LookupMethod.ByName))
398     success = stationProvider.lookupStations(name);
399 torben 319
400 torben 381 Location dummy = new Location("gps");
401 torben 319 List<StationBean> stations = stationProvider.getStations();
402 torben 381
403     for (StationBean station : stations) {
404 torben 317 String addr = lookupAddress(station.getLatitude(), station.getLongitude());
405     station.setAddress(addr);
406 torben 381
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 torben 317
414 torben 241 return null;
415     }
416    
417     @Override
418     protected void onPostExecute(Void result) {
419     super.onPostExecute(result);
420 torben 319 dialog.dismiss();
421    
422     if (success) {
423     if (stationProvider.getStations().size() == 0)
424 torben 336 MessageBox.showMessage(StationList.this, "No stations found!"); // this should not be possible !?!
425 torben 319 stations = stationProvider.getStations();
426     adapter.setStations( stations );
427    
428     } else { //communication or parse errors
429 torben 336 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 torben 319 }
451 torben 241 }
452     }
453 torben 237 }

  ViewVC Help
Powered by ViewVC 1.1.20