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

  ViewVC Help
Powered by ViewVC 1.1.20