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

  ViewVC Help
Powered by ViewVC 1.1.20