/[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 1025 - (show annotations) (download)
Tue Aug 31 08:49:15 2010 UTC (13 years, 8 months ago) by torben
File size: 16343 byte(s)
Re-order onDestroy  so they are shut down in right order
1 package dk.thoerup.traininfo;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6
7 import android.app.Activity;
8 import android.app.AlertDialog;
9 import android.app.Dialog;
10 import android.app.ListActivity;
11 import android.app.ProgressDialog;
12 import android.content.DialogInterface;
13 import android.content.Intent;
14 import android.content.SharedPreferences;
15 import android.content.SharedPreferences.Editor;
16 import android.location.Location;
17 import android.os.AsyncTask;
18 import android.os.Bundle;
19 import android.os.Handler;
20 import android.os.Message;
21
22 import android.view.ContextMenu;
23 import android.view.LayoutInflater;
24 import android.view.Menu;
25 import android.view.MenuItem;
26 import android.view.View;
27 import android.view.ContextMenu.ContextMenuInfo;
28 import android.view.View.OnCreateContextMenuListener;
29 import android.widget.AdapterView;
30 import android.widget.EditText;
31 import android.widget.ListView;
32 import android.widget.Toast;
33 import dk.thoerup.traininfo.provider.ProviderFactory;
34 import dk.thoerup.traininfo.provider.StationProvider;
35 import dk.thoerup.traininfo.stationmap.GeoPair;
36 import dk.thoerup.traininfo.stationmap.StationMapView;
37 import dk.thoerup.traininfo.util.IntSet;
38 import dk.thoerup.traininfo.util.MessageBox;
39
40 import static dk.thoerup.traininfo.R.string.*;
41
42 public class StationList extends ListActivity {
43 public static final int GOTLOCATION = 1001;
44 public static final int GOTSTATIONLIST = 1002;
45 public static final int NOPROVIDER = 1003;
46 public static final int LOCATIONFIXTIMEOUT = 1004;
47
48 public static final int OPTIONS_MAP = 2003;
49 public static final int OPTIONS_GPSINFO = 2004;
50
51 public static final int DLG_PROGRESS = 3001;
52 public static final int DLG_STATIONNAME = 3002;
53
54
55 public static final int GPS_TIMEOUT_MS = 15000; //how long are we willing to wait for gps fix -in milliseconds
56
57
58 static enum LookupMethod {
59 ByLocation,
60 ByName,
61 ByList,
62 MethodNone
63 }
64
65
66 String dialogMessage = "";
67 ProgressDialog dialog;
68 LocationLookup locationLookup = null;
69 FindStationsTask findStationsTask;
70 StationsFetchedHandler stationsFetched = new StationsFetchedHandler();
71
72 GeoPair location = new GeoPair();
73
74 boolean isLaunchedforShortcut;
75 boolean isRunning = false;
76 List<StationBean> stations = new ArrayList<StationBean>();
77
78 StationProvider stationProvider = ProviderFactory.getStationProvider();
79
80 StationListAdapter adapter = null;
81
82 FavoritesMenu contextMenu = new FavoritesMenu();
83 IntSet favorites = new IntSet();
84
85 WelcomeScreen.ListType listType;
86 SharedPreferences prefs;
87
88 ///////////////////////////////////////////////////////////////////////////////////////////
89 //Activity call backs
90
91 @SuppressWarnings("unchecked")
92 @Override
93 public void onCreate(Bundle savedInstanceState) {
94 super.onCreate(savedInstanceState);
95 setContentView(R.layout.stationlist);
96
97
98 adapter = new StationListAdapter(this);
99 setListAdapter(adapter);
100
101 ListView lv = getListView();
102 lv.setOnCreateContextMenuListener(contextMenu);
103
104 locationLookup = new LocationLookup(this, stationsFetched);
105
106
107 prefs = getSharedPreferences("TrainStation", 0);
108 String favoriteString = prefs.getString("favorites", "");
109 if (! favoriteString.equals("") ) {
110 favorites.fromString(favoriteString);
111 }
112
113 listType = (WelcomeScreen.ListType) getIntent().getSerializableExtra("type");
114 setTitle();
115
116 isLaunchedforShortcut = getIntent().getBooleanExtra("shortcut", false);
117
118 if (savedInstanceState == null) {
119
120
121 switch (listType) {
122 case ListNearest:
123 startLookup();
124 break;
125 case ListSearch:
126 showDialog(DLG_STATIONNAME);
127 break;
128 case ListFavorites:
129 startFavoriteLookup();
130 break;
131 default:
132 // Not possible !?!
133 }
134
135 } else {
136 stations = (ArrayList<StationBean>) savedInstanceState.getSerializable("stations");
137 adapter.setStations(stations);
138 location = (GeoPair) savedInstanceState.getSerializable("location");
139 }
140
141 }
142
143
144 @Override
145 protected void onDestroy() {
146 super.onDestroy();
147
148 isRunning = false;
149
150 if (locationLookup != null) {
151 locationLookup.stopSearch();
152 }
153 if (findStationsTask != null) {
154 findStationsTask.cancel(true);
155 }
156 }
157
158
159 protected void setTitle() {
160 String dialogTitle = getResources().getString(app_name);
161 switch (listType) {
162 case ListNearest:
163 dialogTitle += " - " + getString(stationlist_nearbystations);
164 break;
165 case ListSearch:
166 dialogTitle += " - " + getString(stationlist_search);
167 break;
168 case ListFavorites:
169 dialogTitle += " - " + getString(stationlist_favorites);
170 break;
171 default:
172 dialogTitle = "";//not possible
173 }
174
175 setTitle(dialogTitle);
176
177 }
178
179
180
181 @Override
182 public void onSaveInstanceState(Bundle outState)
183 {
184 if (dialog != null && dialog.isShowing())
185 dialog.dismiss();
186 outState.putSerializable("stations", (ArrayList<StationBean>) stations);
187 outState.putSerializable("location", location);
188
189 }
190
191
192
193 @Override
194 public boolean onCreateOptionsMenu(Menu menu) {
195 MenuItem item;
196
197 item = menu.add(0, OPTIONS_MAP, 0, getString(stationlist_stationmap));
198 item.setIcon(android.R.drawable.ic_menu_mapmode);
199
200 item = menu.add(0, OPTIONS_GPSINFO, 0, getString(stationlist_gpsinfo));
201 item.setIcon(android.R.drawable.ic_menu_mapmode);
202
203 return true;
204 }
205
206 @Override
207 public boolean onOptionsItemSelected(MenuItem item) {
208 boolean retval = true;
209
210 //TODO: Cleanup
211 switch (item.getItemId()) {
212 case OPTIONS_MAP:
213
214 Intent intent = new Intent(this,StationMapView.class);
215
216 ArrayList<GeoPair> stationPoints = new ArrayList<GeoPair>();
217 for (StationBean st : stations ) {
218 stationPoints.add( new GeoPair(st.getLatitude(), st.getLongitude(), st.getName()) );
219 }
220
221 intent.putExtra("stations", stationPoints);
222
223 startActivity(intent);
224 break;
225 case OPTIONS_GPSINFO:
226 Location loc = locationLookup.getLocation();
227 StringBuffer message = new StringBuffer();
228 message.append( getString(stationlist_locationinfo) ).append(":\n");
229 if (loc != null) {
230 message.append( getString(stationlist_obtainedby) ).append( loc.getProvider() ).append("\n");
231 message.append( getString(stationlist_accuracy) ).append( (int)loc.getAccuracy()).append("m\n");
232 message.append( getString(stationlist_latitude) ).append( (float)loc.getLatitude()).append("\n");
233 message.append( getString(stationlist_longitude) ).append( (float)loc.getLongitude() ).append("\n");
234 } else {
235 message.append( getString(stationlist_nolocation) );
236 }
237
238 MessageBox.showMessage(this, message.toString(), false);
239 break;
240 default:
241 retval = super.onOptionsItemSelected(item);
242 }
243
244 return retval;
245 }
246
247
248
249 @Override
250 public boolean onContextItemSelected(MenuItem item) {
251 contextMenu.onContextItemSelected(item);
252 return true;
253
254
255 }
256
257 public void showMessageAndClose(String message) {
258 AlertDialog.Builder builder = new AlertDialog.Builder(this);
259 builder.setMessage(message)
260 .setCancelable(false)
261 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
262 public void onClick(DialogInterface dialog, int id) {
263 dialog.dismiss();
264 StationList.this.finish();
265 }
266 })
267 .show();
268 }
269
270
271
272
273 @Override
274 protected Dialog onCreateDialog(int id) {
275 switch (id) {
276 case DLG_PROGRESS:
277 ProgressDialog dlg = new ProgressDialog(this);
278 dlg.setMessage( getString(stationlist_waitforlocation) );
279 dlg.setCancelable(false);
280 return dlg;
281 case DLG_STATIONNAME:
282 LayoutInflater factory = LayoutInflater.from(this);
283 final View rootView = factory.inflate(R.layout.textinput, null);
284
285
286 AlertDialog.Builder builder = new AlertDialog.Builder(this);
287
288 builder.setTitle( getString(stationlist_stationsearch) );
289 builder.setView(rootView);
290 builder.setCancelable(true);
291 builder.setPositiveButton( getString(generic_search), new DialogInterface.OnClickListener() {
292 public void onClick(DialogInterface dialog, int which) {
293 EditText et = (EditText) rootView.findViewById(R.id.EditText);
294 dialog.dismiss();
295 String search = et.getText().toString().trim();
296 if (search.length() >= 2) {
297 startNameSearch(search);
298 } else {
299 showMessageAndClose( getString(stationlist_twocharmin) );
300 }
301 }
302 });
303 builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
304 public void onClick(DialogInterface dialog, int which) {
305 dialog.dismiss();
306 StationList.this.finish(); // Close this Activity
307 }
308 });
309 return builder.create();
310
311 default:
312 return super.onCreateDialog(id);
313 }
314
315 }
316
317
318 @Override
319 protected void onPrepareDialog(int id, Dialog dialog) {
320 super.onPrepareDialog(id, dialog);
321 switch (id) {
322 case DLG_PROGRESS:
323 this.dialog = (ProgressDialog) dialog;
324 if (!dialogMessage.equals("")) {
325 this.dialog.setMessage(dialogMessage);
326 dialogMessage = "";
327 }
328 break;
329 }
330 }
331
332 @Override
333 protected void onListItemClick(ListView l, View v, int position, long id) {
334 super.onListItemClick(l, v, position, id);
335
336 StationBean station = stations.get(position);
337
338 if (isLaunchedforShortcut == true) {
339 Intent i = new Intent();
340 i.putExtra("station", station);
341 setResult(Activity.RESULT_OK, i);
342 finish();
343 } else {
344 Intent intent = new Intent(this, DepartureList.class);
345 intent.putExtra("stationbean", station);
346 startActivity(intent);
347 }
348 }
349
350 /////////////////////////////////////////////////////////////
351 //
352
353 public void startLookup() {
354 isRunning = true;
355 dialogMessage = getString( stationlist_waitforlocation );
356 showDialog(DLG_PROGRESS);
357
358 locationLookup.locateStations();
359 stationsFetched.sendEmptyMessageDelayed(LOCATIONFIXTIMEOUT, GPS_TIMEOUT_MS);
360 }
361
362 void startNameSearch(String name) {
363 dialogMessage = getString( stationlist_findbyname );
364 showDialog(DLG_PROGRESS);
365
366 findStationsTask = new FindStationsTask();
367 findStationsTask.searchByName(name);
368 findStationsTask.execute();
369
370 }
371
372 public void startFavoriteLookup() {
373
374 if (favorites.size() > 0) {
375 dialogMessage = getString( stationlist_loadfavorites );
376 showDialog(DLG_PROGRESS);
377
378 findStationsTask = new FindStationsTask();
379 findStationsTask.searchByIds( favorites.toString() );
380 findStationsTask.execute();
381 } else {
382 showMessageAndClose( getString( stationlist_nofavorites ) );
383 }
384 }
385
386
387
388 void startLocatorTask()
389 {
390 dialogMessage = getString( stationlist_findingnearby );
391 showDialog(DLG_PROGRESS);
392
393 findStationsTask = new FindStationsTask();
394 findStationsTask.searchByLocation( locationLookup.getLocation() );
395 findStationsTask.execute();
396 }
397
398
399 ////////////////////////////////////////////////////////////////////////////
400 // Inner classes
401
402 class StationsFetchedHandler extends Handler {
403 @Override
404 public void handleMessage(Message msg) {
405
406 switch (msg.what) {
407 case GOTLOCATION:
408 dismissDialog(DLG_PROGRESS);
409
410 startLocatorTask();
411 location = GeoPair.fromLocation( locationLookup.getLocation() );
412
413 break;
414
415 case NOPROVIDER:
416 dismissDialog(DLG_PROGRESS);
417 MessageBox.showMessage(StationList.this, getString(stationlist_nolocationprovider), true );
418 //StationList.this.finish();
419 break;
420 case LOCATIONFIXTIMEOUT:
421 if (isRunning) {
422 locationLookup.stopSearch();
423 if (locationLookup.hasLocation()) {
424 stationsFetched.sendEmptyMessage( GOTLOCATION );
425 } else {
426 dismissDialog(DLG_PROGRESS);
427
428 AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);
429 builder.setMessage( getString( stationlist_gpstimeout) );
430 builder.setCancelable(true);
431 builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
432 public void onClick(DialogInterface dialog, int id) {
433 dialog.dismiss();
434 startLookup();
435
436 }
437 });
438 builder.setNegativeButton( getString(generic_cancel), new DialogInterface.OnClickListener() {
439 public void onClick(DialogInterface dialog, int id) {
440 dialog.dismiss();
441 }
442 });
443 builder.show();
444
445 }
446 }
447 break;
448 }
449 isRunning = false;
450 }
451 };
452
453
454 class FindStationsTask extends AsyncTask<Void,Void,Void> {
455
456 LookupMethod method = LookupMethod.MethodNone;
457 String name;
458 Location loc;
459 String ids;
460
461 public void searchByName(String n) {
462
463 method = LookupMethod.ByName;
464 name = n;
465 }
466
467 public void searchByLocation(Location l) {
468 method = LookupMethod.ByLocation;
469 loc = l;
470 }
471
472 public void searchByIds(String id) {
473
474 method = LookupMethod.ByList;
475 ids = id;
476 }
477
478 @Override
479 protected void onPreExecute() {
480
481 if (method.equals(LookupMethod.MethodNone))
482 throw new RuntimeException("Method not set");
483 super.onPreExecute();
484 }
485
486 @Override
487 protected Void doInBackground(Void... params) {
488
489 switch (method) {
490 case ByLocation:
491 stations = stationProvider.lookupStations(loc);
492 break;
493 case ByName:
494 stations = stationProvider.lookupStationsByName(name);
495 break;
496 case ByList:
497 stations = stationProvider.lookupStationsByIds(ids);
498 break;
499 default:
500 stations = null; // not possible
501 }
502
503
504 return null;
505 }
506
507 @Override
508 protected void onPostExecute(Void result) {
509 super.onPostExecute(result);
510 dialog.dismiss();
511
512
513 if (stations != null) {
514 if (stations.size() == 0) {
515 showMessageAndClose(getString(stationlist_nostations));
516 }
517
518 StationList.this.getListView().invalidateViews();
519 adapter.setStations( stations );
520
521
522 } else { //communication or parse errors
523 AlertDialog.Builder builder = new AlertDialog.Builder(StationList.this);
524 builder.setMessage(getString(stationlist_fetcherror));
525 builder.setCancelable(true);
526 builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
527 public void onClick(DialogInterface dialog, int id) {
528 dialog.dismiss();
529
530 Runnable runner = null;
531 switch (method) {
532 case ByLocation:
533 runner = new Runnable() {
534 @Override
535 public void run() {
536 startLocatorTask();
537 }
538 };
539 break;
540 case ByName:
541 runner = new Runnable() {
542 @Override
543 public void run() {
544 startNameSearch( FindStationsTask.this.name );
545 }
546 };
547 break;
548 case ByList:
549 runner = new Runnable() {
550 @Override
551 public void run() {
552 startFavoriteLookup();
553 }
554 };
555 break;
556 }
557
558 stationsFetched.post( runner );
559 }
560 });
561 builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
562 public void onClick(DialogInterface dialog, int id) {
563 dialog.dismiss();
564 StationList.this.finish();
565 }
566 });
567
568 builder.show();
569 }
570 }
571 }
572
573
574 class FavoritesMenu implements OnCreateContextMenuListener {
575 private final static int FAVORITES_ADD = 9001;
576 private final static int FAVORITES_REMOVE = 9002;
577
578 private int selectedPosition;
579
580
581 @Override
582 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
583
584 AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
585 selectedPosition = info.position;
586 int stationID = stations.get(selectedPosition).getId();
587
588 if (!favorites.contains(stationID)) {
589 menu.add(0, FAVORITES_ADD, 0, getString(stationlist_addfavorite) );
590 } else {
591 menu.add(0, FAVORITES_REMOVE, 0, getString(stationlist_removefavorite) );
592 }
593
594 }
595
596 public void onContextItemSelected(MenuItem item) {
597 StationBean sb = stations.get(selectedPosition);
598
599 int stationID = sb.getId();
600 if (item.getItemId() == FAVORITES_ADD) {
601 favorites.add(stationID);
602 Toast.makeText(StationList.this, getString(stationlist_stationadded), Toast.LENGTH_SHORT).show();
603 } else {
604
605 favorites.remove(stationID);
606 Toast.makeText(StationList.this, getString(stationlist_stationremoved), Toast.LENGTH_SHORT).show();
607
608
609 if (listType.equals( WelcomeScreen.ListType.ListFavorites) ) {
610 stations.remove(selectedPosition);
611 adapter.notifyDataSetChanged();
612 }
613 }
614 Editor ed = prefs.edit();
615 ed.putString("favorites", favorites.toString());
616 ed.commit();
617 }
618 }
619 }

  ViewVC Help
Powered by ViewVC 1.1.20