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

  ViewVC Help
Powered by ViewVC 1.1.20