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

  ViewVC Help
Powered by ViewVC 1.1.20