/[projects]/android/TrainInfo/src/dk/thoerup/traininfo/DepartureList.java
ViewVC logotype

Diff of /android/TrainInfo/src/dk/thoerup/traininfo/DepartureList.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 239 by torben, Sun Aug 9 09:09:16 2009 UTC revision 1055 by torben, Tue Sep 14 16:30:16 2010 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfo;  package dk.thoerup.traininfo;
2    
3    import static dk.thoerup.traininfo.R.string.departurelist_fetcharrivals;
4    import static dk.thoerup.traininfo.R.string.departurelist_fetchdepartures;
5    import static dk.thoerup.traininfo.R.string.generic_cancel;
6    import static dk.thoerup.traininfo.R.string.generic_retry;
7    
8  import java.text.NumberFormat;  import java.text.NumberFormat;
 import java.util.List;  
9    
10    import android.app.AlertDialog;
11  import android.app.Dialog;  import android.app.Dialog;
12  import android.app.ListActivity;  import android.app.ListActivity;
13  import android.app.ProgressDialog;  import android.app.ProgressDialog;
14    import android.content.DialogInterface;
15  import android.content.Intent;  import android.content.Intent;
16    import android.graphics.Typeface;
17  import android.net.Uri;  import android.net.Uri;
18  import android.os.AsyncTask;  import android.os.AsyncTask;
19  import android.os.Bundle;  import android.os.Bundle;
20    import android.util.Log;
21    import android.view.Menu;
22    import android.view.MenuItem;
23  import android.view.View;  import android.view.View;
24    import android.view.View.OnClickListener;
25    import android.widget.Button;
26  import android.widget.ListView;  import android.widget.ListView;
27    import android.widget.TableLayout;
28    import android.widget.TableRow;
29  import android.widget.TextView;  import android.widget.TextView;
 import android.widget.Toast;  
 import dk.thoerup.traininfo.provider.DepartureFactory;  
30  import dk.thoerup.traininfo.provider.DepartureProvider;  import dk.thoerup.traininfo.provider.DepartureProvider;
31    import dk.thoerup.traininfo.provider.MetroProvider;
32    import dk.thoerup.traininfo.provider.ProviderFactory;
33    import dk.thoerup.traininfo.provider.MetroProvider.MetroBean;
34    import dk.thoerup.traininfo.provider.MetroProvider.MetroEntry;
35    import dk.thoerup.traininfo.util.MessageBox;
36    
37  public class DepartureList extends ListActivity {  public class DepartureList extends ListActivity {
38    
39          public static final int DLG_PROGRESS = 1;          public static final int DLG_PROGRESS = 1;
40          public static final int DLG_DETAILS = 2;          static final int MENU_MAP = 100;
41            static final int MENU_NOTIFICATIONS = 101;
42            
43                    
44          DepartureListAdapter adapter;          DepartureListAdapter adapter;
45          DepartureProvider provider;          DepartureProvider provider;
46          List<DepartureBean> departures;          DepartureBean departures;
47                    
48          static int itemId;          MetroBean metroBean;
49          static DepartureBean currentDeparture;          MetroProvider metro;
50            
51            int selectedItemId;
52            //DepartureBean currentDeparture;
53                    
54          ProgressDialog pgDialog;          ProgressDialog pgDialog;
55                    
56          DepartureFetcher fetcher;          DepartureFetcher fetcher;
57            MetroFetcher metroFetcher;
58    
59            StationBean station;
60                    
61          double latitude,longitude;          boolean arrival = false;
62            
63            int commFailCounter = 0;
64    
65          @Override          @Override
66          protected void onCreate(Bundle savedInstanceState) {          protected void onCreate(Bundle savedInstanceState) {
67                  super.onCreate(savedInstanceState);                  super.onCreate(savedInstanceState);
# Line 44  public class DepartureList extends ListA Line 71  public class DepartureList extends ListA
71                  setListAdapter(adapter);                  setListAdapter(adapter);
72                                    
73                  Intent launchedBy = getIntent();                  Intent launchedBy = getIntent();
74            
75                    station = (StationBean) launchedBy.getSerializableExtra("stationbean");
76                                    
77                  latitude = launchedBy.getDoubleExtra("latitude", 0.0);                  ((TextView) findViewById(R.id.stationName)).setText( station.getName() );
78                  longitude = launchedBy.getDoubleExtra("longitude", 0.0);  
79    
80                    ((TextView) findViewById(R.id.stationAddr)).setText( station.getAddress() );
81                                    
82                  String name = launchedBy.getStringExtra("name");                  final Button departureBtn = (Button) findViewById(R.id.departurebtn);
83                  ((TextView) findViewById(R.id.stationName)).setText( name );                  final Button arrivalBtn = (Button) findViewById(R.id.arrivalbtn);
84                    final Button metroBtn = (Button) findViewById(R.id.metrobtn);
85                    
86                    final View metroView = findViewById(R.id.metroonly);
87                    
88                    departureBtn.setOnClickListener( new OnClickListener() {
89                            @Override
90                            public void onClick(View arg0) {        
91                                    arrivalBtn.setBackgroundResource(R.drawable.custom_button);
92                                    departureBtn.setBackgroundResource(R.drawable.custom_button_hilight);
93                                    metroBtn.setBackgroundResource(R.drawable.custom_button);
94                                    
95                                    getListView().setVisibility( View.VISIBLE );            
96                                    metroView.setVisibility( View.GONE );
97                                    arrival = false;
98                                    startDepartureFetcher();
99                            }
100                    });
101                    arrivalBtn.setOnClickListener( new OnClickListener() {
102                            @Override
103                            public void onClick(View arg0) {        
104                                    arrivalBtn.setBackgroundResource(R.drawable.custom_button_hilight);
105                                    departureBtn.setBackgroundResource(R.drawable.custom_button);
106                                    metroBtn.setBackgroundResource(R.drawable.custom_button);
107                                    
108                                    getListView().setVisibility( View.VISIBLE );            
109                                    metroView.setVisibility( View.GONE );
110                                    arrival = true;                
111                                    startDepartureFetcher();
112                            }
113                    });
114                    
115                    metroBtn.setOnClickListener( new OnClickListener() {                    
116                            @Override
117                            public void onClick(View v) {
118                                    arrivalBtn.setBackgroundResource(R.drawable.custom_button);
119                                    departureBtn.setBackgroundResource(R.drawable.custom_button);
120                                    metroBtn.setBackgroundResource(R.drawable.custom_button_hilight);
121                                    
122                                    getListView().setVisibility( View.GONE );              
123                                    metroView.setVisibility( View.VISIBLE );
124                                    startMetroFetcher();
125                            }
126                    });
127                    
128                    
129                    
130                    
131                    // findViewById(R.id.header).setOnClickListener( mapLauncher );
132                    
133                    int distance = station.getDistance();
134                    if (distance != 0) {
135                            NumberFormat format = NumberFormat.getNumberInstance();
136                            format.setMaximumFractionDigits(1);
137                            format.setMinimumFractionDigits(1);
138                    
139                            ((TextView) findViewById(R.id.stationDistance)).setText( format.format((double)distance/1000.0) + " km." );
140                    } else {
141                            ((TextView) findViewById(R.id.stationDistance)).setVisibility(View.GONE);
142                    }
143            
144                    ProviderFactory.purgeOldEntries(); //cleanup before fetching more data
145                                    
146                  String addr = launchedBy.getStringExtra("address");                  Log.e("Station", station.toCSV() );
                 ((TextView) findViewById(R.id.stationAddr)).setText( addr );  
147                                    
148                  findViewById(R.id.header).setOnClickListener( mapLauncher );                  if (station.isMetro() == false) {
149                                            metroBtn.setVisibility( View.GONE );
150                  NumberFormat format = NumberFormat.getNumberInstance();                  }
                 format.setMaximumFractionDigits(1);  
                 format.setMinimumFractionDigits(1);  
                 int distance = launchedBy.getIntExtra("distance", 0);  
                 ((TextView) findViewById(R.id.stationDistance)).setText( format.format((double)distance/1000.0) + " km." );  
151                    
152                    metro = ProviderFactory.getMetroProvider();
153                                    
154                  showDialog(DLG_PROGRESS);                  if (station.isRegional() == false && station.isSTrain() == false) {
155                  provider = DepartureFactory.getProvider();                          getListView().setVisibility( View.GONE );              
156                                            metroView.setVisibility( View.VISIBLE );
157                  fetcher = new DepartureFetcher();                          
158                  fetcher.execute(name);                          departureBtn.setVisibility( View.GONE );
159                            arrivalBtn.setVisibility(View.GONE);
160                            metroBtn.setVisibility( View.GONE );
161                            
162                            if (savedInstanceState == null) {
163                                    startMetroFetcher();
164                            } else {
165                                    metroBean = (MetroBean) savedInstanceState.getSerializable("metro");
166                                    loadMetroData();
167                            }
168                            
169                    } else {
170                            provider = ProviderFactory.getDepartureProvider();
171                            
172                            if (savedInstanceState == null) {
173                                    startDepartureFetcher();
174                            } else {
175                                    departures = (DepartureBean) savedInstanceState.getSerializable("departures");
176                                    
177                                    if ( (departures != null) && (departures.entries != null) ) {
178                                            adapter.setDepartures(departures.entries);
179                                    }
180                                    selectedItemId = savedInstanceState.getInt("selectedItemId");
181                                    
182                                    if ( hasNotifications() ) {
183                                            findViewById(R.id.notifIcon).setVisibility(View.VISIBLE);
184                                    }
185                                    
186                            }
187                    }
188          }          }
189                    
190            boolean hasNotifications() {
191                    return (departures != null && departures.notifications.size() > 0);
192            }
193            
194        @Override
195        public void onSaveInstanceState(Bundle outState)
196        {
197            if (pgDialog != null && pgDialog.isShowing())
198                    dismissDialog(DLG_PROGRESS);
199    
200            outState.putInt("selectedItemId", selectedItemId);
201            
202            outState.putSerializable("departures",  departures);
203            outState.putSerializable("metro", metroBean);
204        }
205        
206        
207            
208            @Override
209            protected void onDestroy() {
210                    super.onDestroy();
211                    
212                    if (fetcher != null) {
213                            fetcher.cancel(true);
214                    }
215                    
216                    if (metroFetcher != null) {
217                            metroFetcher.cancel(true);
218                    }
219            }
220    
221          @Override          @Override
222          protected void onListItemClick(ListView l, View v, int position, long id) {          protected void onListItemClick(ListView l, View v, int position, long id) {
223                  super.onListItemClick(l, v, position, id);                  super.onListItemClick(l, v, position, id);
224                    
225                    selectedItemId = position;
226                    
227                    DepartureEntry dep = departures.entries.get(selectedItemId);
228                    
229                  currentDeparture = departures.get(position);                  Intent intent = new Intent(this, TimetableList.class);
230                  showDialog(DLG_DETAILS);                                  intent.putExtra("departure", dep);
231                    
232                    startActivity(intent);
233                                    
234          }          }
235                    
236    
237          @Override          @Override
238          protected void onPrepareDialog(int id, Dialog dialog) {          protected void onPrepareDialog(int id, Dialog dialog) {
239                  super.onPrepareDialog(id, dialog);                  super.onPrepareDialog(id, dialog);
240                            
241                  switch (id) {                  switch (id) {
                 case DLG_DETAILS:  
                         ((TextView)dialog.findViewById(R.id.Time)).setText(currentDeparture.getTime());  
                         ((TextView)dialog.findViewById(R.id.Destination)).setText( currentDeparture.getDestination());  
                         ((TextView)dialog.findViewById(R.id.Origin)).setText(currentDeparture.getOrigin());  
                         ((TextView)dialog.findViewById(R.id.Location)).setText(currentDeparture.getLocation());  
                         ((TextView)dialog.findViewById(R.id.Updated)).setText(currentDeparture.getLastUpdateString());  
                         ((TextView)dialog.findViewById(R.id.Status)).setText(currentDeparture.getStatus());  
                         ((TextView)dialog.findViewById(R.id.Note)).setText(currentDeparture.getNote());  
                         break;  
242                  case DLG_PROGRESS:                  case DLG_PROGRESS:
243                          pgDialog = (ProgressDialog) dialog;                          pgDialog = (ProgressDialog) dialog;
244                            int messageId = arrival == false ? departurelist_fetchdepartures : departurelist_fetcharrivals;
245                            pgDialog.setMessage( getString(messageId) );
246                          break;                          break;
247                  }                  }
248          }          }
# Line 103  public class DepartureList extends ListA Line 251  public class DepartureList extends ListA
251          protected Dialog onCreateDialog(int id) {          protected Dialog onCreateDialog(int id) {
252                  switch (id) {                  switch (id) {
253                  case DLG_PROGRESS:                  case DLG_PROGRESS:
254    
255                          ProgressDialog dlg = new ProgressDialog(this);                          ProgressDialog dlg = new ProgressDialog(this);
                         dlg.setMessage("Fetch departure data");  
256                          dlg.setCancelable(true);                          dlg.setCancelable(true);
257                          return dlg;                          return dlg;                    
                 case DLG_DETAILS:  
                         //Context mContext = getApplicationContext();  
                         Dialog dialog = new Dialog(this);  
                         dialog.setCancelable(true);  
   
                         dialog.setContentView(R.layout.departuredetails);  
                         dialog.setTitle("Departure details");  
   
                         View root = dialog.findViewById(R.id.layout_root);  
                         root.setOnClickListener( new DialogDismisser(dialog) );  
                         return dialog;                    
258                  default:                  default:
259                          return super.onCreateDialog(id);                                          return super.onCreateDialog(id);                
260                  }                  }
261          }          }
262            
263            
264    
265    
266    
267            @Override
268            public boolean onCreateOptionsMenu(Menu menu) {
269                    MenuItem item;
270                    
271                    item = menu.add(0, MENU_MAP, 0, getString(R.string.departurelist_showonmap) );
272                    item.setIcon(android.R.drawable.ic_menu_mapmode);
273                    
274                    item = menu.add(0, MENU_NOTIFICATIONS, 0, getString(R.string.departurelist_notifications) );
275                    item.setIcon(android.R.drawable.ic_menu_info_details);
276                    
277                    
278                    boolean notifEnabled = hasNotifications();
279                    item.setEnabled(notifEnabled);
280                    
281    
282                    return true;
283            }
284    
285            @Override
286            public boolean onOptionsItemSelected(MenuItem item) {          
287                    boolean res;
288                    switch(item.getItemId()) {
289                    case MENU_MAP:
290                            Uri uri = Uri.parse("geo:" + station.getLatitude() + "," + station.getLongitude());
291                            startActivity( new Intent(Intent.ACTION_VIEW, uri));
292                            res = true;
293                            break;
294                    case MENU_NOTIFICATIONS:
295                            Intent i = new Intent(this,dk.thoerup.traininfo.NotificationList.class);
296                            i.putExtra(NotificationList.EXTRA_NOTIFICATIONS, departures.notifications);
297                            startActivity(i);
298                            res = true;
299                            break;
300                    default:
301                            res = super.onOptionsItemSelected(item);
302                    }
303                    return res;
304            }
305    
306            void startDepartureFetcher() {
307                    showDialog(DLG_PROGRESS);
308                    fetcher = new DepartureFetcher();
309                    fetcher.execute(station.getId());
310            }
311            
312            void startMetroFetcher() {
313                    showDialog(DLG_PROGRESS);
314                    metroFetcher = new MetroFetcher();
315                    metroFetcher.execute(station.getId());          
316            }
317            
318          class DialogDismisser implements View.OnClickListener {          class DialogDismisser implements View.OnClickListener {
319    
320                  Dialog dlg;                  Dialog dlg;
# Line 134  public class DepartureList extends ListA Line 326  public class DepartureList extends ListA
326                  public void onClick(View v) {                  public void onClick(View v) {
327                          if (dlg.isShowing())                          if (dlg.isShowing())
328                                  dlg.dismiss();                                  dlg.dismiss();
329                  }                  }      
330          }          }
331                    
332          View.OnClickListener mapLauncher = new View.OnClickListener() {          /*View.OnClickListener mapLauncher = new View.OnClickListener() {
333                  @Override                  @Override
334                  public void onClick(View v) {                  public void onClick(View v) {                  
335                          Uri uri = Uri.parse("geo:" + latitude + "," + longitude);                          Uri uri = Uri.parse("geo:" + station.getLatitude() + "," + station.getLongitude());
336                          startActivity( new Intent(Intent.ACTION_VIEW, uri));                          startActivity( new Intent(Intent.ACTION_VIEW, uri));
337                  }                  }
338          };          };*/
339    
340    
341                    
342            class DepartureFetcher extends AsyncTask<Integer, Void, Void> {
343    
344                    @Override
345                    protected void onPostExecute(Void result) {
346                            super.onPostExecute(result);
347                            
348                            
349                            pgDialog.dismiss();
350                            
351                            if (departures != null) {
352                                    commFailCounter = 0;
353                                    DepartureList.this.getListView().setVisibility(View.GONE); //Experimental, inspired by http://osdir.com/ml/Android-Developers/2010-04/msg01198.html
354                                    adapter.setDepartures(departures.entries);
355                                    DepartureList.this.getListView().setVisibility(View.VISIBLE);
356                                    
357                                    
358                                    if ( hasNotifications() ) {
359                                            findViewById(R.id.notifIcon).setVisibility(View.VISIBLE);
360                                    }
361                                    
362                                    if (departures.entries.size() == 0) {
363                                            MessageBox.showMessage(DepartureList.this, "No departures found", true);
364                                    }
365                            } else { // communication or parse error
366                                    commFailCounter++;
367                                    AlertDialog.Builder builder = new AlertDialog.Builder(DepartureList.this);                                              
368                                    builder.setMessage("Error finding departures");
369                                    builder.setCancelable(true);
370                                    if (commFailCounter < 3) {
371                                            builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
372                                                    public void onClick(DialogInterface dialog, int id) {
373                                                            dialog.dismiss();
374                                                            startDepartureFetcher();
375                                                            
376                                                    }
377                                            });
378                                    }
379                                    builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
380                                            public void onClick(DialogInterface dialog, int id) {
381                                                    dialog.dismiss();
382                                                    DepartureList.this.finish();
383                                            }                                                      
384                                    });
385                                    
386                                    try {
387                                            builder.show();
388                                    } catch (android.view.WindowManager.BadTokenException e) {                                      
389                                            Log.i("DepartureList", "BadTokenException"); // this can happen if the user switched away from this activity, while doInBackground was running
390                                    }                              
391                            }
392                    }
393    
394                    @Override
395                    protected Void doInBackground(Integer... params) {
396                            departures = provider.lookupDepartures(params[0], DepartureList.this.arrival);
397                            return null;
398                    }
399                    
400            }
401                    
402          class DepartureFetcher extends AsyncTask<String, Void, Void> {          public void loadMetroData() {
403                    ((TextView) findViewById(R.id.operations)).setText( metroBean.operationInfo );
404                    ((TextView) findViewById(R.id.plan)).setText( metroBean.plan );
405                    
406                    
407                    TableLayout table = (TableLayout) findViewById(R.id.metrotable);
408                    table.removeAllViews();
409                    
410                    TableRow head = new TableRow(this);
411                    
412                    TextView h1 = new TextView(this);
413                    h1.setText("Metro");
414                    h1.setTypeface( Typeface.defaultFromStyle(Typeface.BOLD));
415                    
416                    
417                    TableRow.LayoutParams params = new TableRow.LayoutParams();
418                    params.span = 2;
419                    head.addView(h1, params);
420                    
421                    
422                    
423                    TextView h2 = new TextView(this);
424                    h2.setTypeface( Typeface.defaultFromStyle(Typeface.BOLD));
425                    h2.setText("Om minutter");
426                    
427                    head.addView(h2,params);
428    
429                    
430                    
431                    table.addView(head);
432    
433                    for (MetroEntry entry : metroBean.entries) {
434                            TableRow row = new TableRow(this);
435                            
436                            Log.e("Test", "" + entry.destination);
437                            
438                            TextView v1 = new TextView(this);
439                            v1.setText( entry.metro );
440                            row.addView(v1);
441                            
442                            TextView v2 = new TextView(this);
443                            v2.setText( entry.destination );
444                            row.addView(v2);
445                    
446                            TextView v3 = new TextView(this);
447                            v3.setText( entry.minutes );
448                            row.addView(v3);
449                            
450                            table.addView(row);
451                            
452                    }
453                    findViewById(R.id.rootView).requestLayout();
454            }
455            
456            class MetroFetcher extends AsyncTask<Integer, Void, Void> {
457                    
458                  @Override                  @Override
459                  protected void onPostExecute(Void result) {                  protected void onPostExecute(Void result) {
460                          super.onPostExecute(result);                          super.onPostExecute(result);
461                                                    
462                          adapter.setDepartures(departures);                          
463                            
464                          pgDialog.dismiss();                          pgDialog.dismiss();
465                                                    
466                          if (departures.size() == 0)                          if (metroBean != null) {
467                                  Toast.makeText(DepartureList.this, "No departures found", Toast.LENGTH_LONG);                                  loadMetroData();
468                            } else { // communication or parse error
469                                    commFailCounter++;
470                                    AlertDialog.Builder builder = new AlertDialog.Builder(DepartureList.this);                                              
471                                    builder.setMessage("Error finding metro data");
472                                    builder.setCancelable(true);
473                                    if (commFailCounter < 3) {
474                                            builder.setPositiveButton(getString(generic_retry), new DialogInterface.OnClickListener() {
475                                                    public void onClick(DialogInterface dialog, int id) {
476                                                            dialog.dismiss();
477                                                            startMetroFetcher();
478                                                            
479                                                    }
480                                            });
481                                    }
482                                    builder.setNegativeButton(getString(generic_cancel), new DialogInterface.OnClickListener() {
483                                            public void onClick(DialogInterface dialog, int id) {
484                                                    dialog.dismiss();
485                                                    DepartureList.this.finish();
486                                            }                                                      
487                                    });
488                                    
489                                    try {
490                                            builder.show();
491                                    } catch (android.view.WindowManager.BadTokenException e) {                                      
492                                            Log.i("DepartureList", "BadTokenException"); // this can happen if the user switched away from this activity, while doInBackground was running
493                                    }                              
494                            }
495                  }                  }
496    
497                  @Override                  @Override
498                  protected Void doInBackground(String... params) {                  protected Void doInBackground(Integer... params) {                      
499                          provider.lookupDepartures(params[0]);                          metroBean = metro.lookupMetroInfo(params[0]);
                         departures = provider.getDepartures();  
500                          return null;                          return null;
501                  }                  }
502                                    
503          }          }
504    
505  }  }

Legend:
Removed from v.239  
changed lines
  Added in v.1055

  ViewVC Help
Powered by ViewVC 1.1.20