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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 419 - (show 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 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;
8 import android.app.Dialog;
9 import android.app.ListActivity;
10 import android.app.ProgressDialog;
11 import android.content.DialogInterface;
12 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;
18 import android.os.Handler;
19 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;
25 import android.widget.EditText;
26 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
44
45 public static final int DLG_PROGRESS = 3001;
46 public static final int DLG_STATIONNAME = 3002;
47
48 /** Called when the activity is first created. */
49 String dialogMessage = "";
50 ProgressDialog dialog;
51 LocationLookup locator = null;
52 LocatorTask locatorTask;
53 StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
54
55 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;
63
64 static enum LookupMethod {
65 ByLocation,
66 ByName,
67 MethodNone
68 }
69
70 ///////////////////////////////////////////////////////////////////////////////////////////
71 //Activity call backs
72
73 @SuppressWarnings("unchecked")
74 @Override
75 public void onCreate(Bundle savedInstanceState) {
76 super.onCreate(savedInstanceState);
77 setContentView(R.layout.main);
78
79
80 adapter = new StationListAdapter(this);
81 setListAdapter(adapter);
82
83 locator = new LocationLookup(this, stationsFetched);
84 if (savedInstanceState == null) {
85 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
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) {
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 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:
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 if (!dialogMessage.equals("")) {
220 this.dialog.setMessage(dialogMessage);
221 dialogMessage = "";
222 }
223 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() {
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) {
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 @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("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;
358 }
359 isRunning = false;
360 }
361 };
362
363
364 class LocatorTask extends AsyncTask<Void,Void,Void> {
365
366 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 public void searchByLocation(Location l) {
379 method = LookupMethod.ByLocation;
380 loc = l;
381 }
382
383 @Override
384 protected void onPreExecute() {
385
386 if (method.equals(LookupMethod.MethodNone))
387 throw new RuntimeException("Method not set");
388 super.onPreExecute();
389 }
390
391 @Override
392 protected Void doInBackground(Void... params) {
393
394 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();
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 }

  ViewVC Help
Powered by ViewVC 1.1.20