/// <summary>
        /// Called periodically to get the next departure time
        /// </summary>
        private void PerformUpdate()
        {
            // Make sure a non-cached set of TrainTrips is used
            TrainTrips.Reset();
            trainJourneyRetrieval.GetJourneys(TrainTrips.SelectedTrip);

            // The update is now in progress, so report this
            Application.Context.SendBroadcast(new Intent(AppWidget.UpdateInProgress));
        }
示例#2
0
        /// <summary>
        /// Renders the visual contents of a specific widget contents into a RemoteViews object
        /// </summary>
        /// <param name="widgetContext">Widget context.</param>
        /// <param name="widgetId">Widget identifier.</param>
        private RemoteViews RenderWidgetContents(Context context, int widgetId)
        {
            // Initialise the persistent storage
            PersistentStorage.StorageMechanism = new StorageMechanism(context);
            PersistentStorage.UseCache         = false;

            // Create a RemoteView for the widget
            RemoteViews widgetView = new RemoteViews(context.PackageName, Resource.Layout.widget);

            // Extract the current trip details and display them.
            // The trip details and selected trip can be changed independently by the main app so a new set of train trip details need to be read
            TrainTrips.Reset();
            TrainTrip selectedTrip = TrainTrips.SelectedTrip;

            if (selectedTrip != null)
            {
                widgetView.SetTextViewText(Resource.Id.widgetTrip, string.Format("{0}:{1}", selectedTrip.FromCode, selectedTrip.ToCode));
            }

            // Extract the next departure time and display it
            DateTime departureTime = NextDeparture.DepartureTime;

            widgetView.SetTextViewText(Resource.Id.widgetDeparture, departureTime.ToString("HH:mm"));

            // Register pending intents for clicking on the displayed fields
            RegisterClicks(context, widgetView);

            // Show the correct image for the running state of the update service
            if (PersistentStorage.GetBoolItem(UpdateInProgressName, false) == true)
            {
                // An update is actually in progress, so show the progress indicator and hide
                // the service status flags
                widgetView.SetViewVisibility(Resource.Id.layoutProgressBar, Android.Views.ViewStates.Visible);
                widgetView.SetViewVisibility(Resource.Id.imageStart, Android.Views.ViewStates.Gone);
                widgetView.SetViewVisibility(Resource.Id.imageStop, Android.Views.ViewStates.Gone);
            }
            else
            {
                // Hide the progress indicator and show the servide state
                widgetView.SetViewVisibility(Resource.Id.layoutProgressBar, Android.Views.ViewStates.Gone);

                if (PersistentStorage.GetBoolItem(UpdateServiceRunningName, false) == true)
                {
                    widgetView.SetViewVisibility(Resource.Id.imageStart, Android.Views.ViewStates.Gone);
                    widgetView.SetViewVisibility(Resource.Id.imageStop, Android.Views.ViewStates.Visible);
                }
                else
                {
                    widgetView.SetViewVisibility(Resource.Id.imageStart, Android.Views.ViewStates.Visible);
                    widgetView.SetViewVisibility(Resource.Id.imageStop, Android.Views.ViewStates.Gone);
                }
            }

            return(widgetView);
        }
        public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
        {
            // Make sure a non-cached set of TrainTrips is used
            TrainTrips.Reset();

            trainJourneyRetrieval.GetJourneys(TrainTrips.SelectedTrip);

            // The update is now in progress, so report this
            Application.Context.SendBroadcast(new Intent(AppWidget.UpdateInProgress));

            return(StartCommandResult.NotSticky);
        }
示例#4
0
        /// <summary>
        /// Called when another activity stated by this activity exits
        /// Because only the AddTripActivity is the only activity started there is no need to check the request code.
        /// </summary>
        /// <param name="requestCode"></param>
        /// <param name="resultCode"></param>
        /// <param name="data"></param>
        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            if (resultCode == Result.Ok)
            {
                // Refresh the spinner adapter
                spinnerAdapter.Clear();
                spinnerAdapter.AddAll(TrainTrips.TripStrings());

                // Assume that the user wants to display results for the added trip, so select it.
                tripSpinner.SetSelection(TrainTrips.Trips.Count - 1);
            }
        }
示例#5
0
        /// <summary>
        /// Validate that the from and to station fileds contain valid stations names, are not the same, and
        /// do not represent a valid trip
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddButtonClicked(object sender, System.EventArgs e)
        {
            bool   validTrip    = true;
            string errorMessage = "";

            // Check for valid station names
            if (Array.IndexOf(StationStorage.StationNames, fromView.Text) < 0)
            {
                errorMessage += string.Format("'{0}' is not a valid station name\n", fromView.Text);
                validTrip     = false;
            }

            if (Array.IndexOf(StationStorage.StationNames, toView.Text) < 0)
            {
                errorMessage += string.Format("'{0}' is not a valid station name\n", toView.Text);
                validTrip     = false;
            }

            if (validTrip == true)
            {
                // Make sure they are not the same
                if (fromView.Text == toView.Text)
                {
                    errorMessage += "Station names cannot be the same\n";
                    validTrip     = false;
                }
            }

            if (validTrip == true)
            {
                // Check for a duplicate trip
                if (TrainTrips.IsDuplicateTrip(fromView.Text, toView.Text) == true)
                {
                    errorMessage += string.Format("A trip from {0} to {1} already exists\n", fromView.Text, toView.Text);
                    validTrip     = false;
                }
            }

            if (validTrip == false)
            {
                // Display the reason why this trip cannot be added
                new AlertDialog.Builder(this)
                .SetTitle("Cannot add trip")
                .SetMessage(errorMessage)
                .SetPositiveButton("OK", (EventHandler <DialogClickEventArgs>)null)
                .Create()
                .Show();
            }
            else
            {
                // Add the trip and close this activity
                TrainTrips.AddTrip(new TrainTrip {
                    From   = fromView.Text, To = toView.Text, FromCode = StationStorage.GetCode(fromView.Text),
                    ToCode = StationStorage.GetCode(toView.Text)
                });
                RecentStations.AddStation(fromView.Text);
                RecentStations.AddStation(toView.Text);

                SetResult(Result.Ok);
                Finish();
            }
        }
示例#6
0
        /// <summary>
        /// Called when a trip item has been long clicked.
        /// Confirm deletion and then delete the item.
        /// This may involve changing the currently selected trip
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TripLongClick(object sender, TripAdapter.LongClickEventArgs e)
        {
            TrainTrip tripToDelete = TrainTrips.Trips[e.TripPosition];

            // Display a confirmation dialogue
            new AlertDialog.Builder(this)
            .SetTitle("Confirm trip deletion")
            .SetMessage(string.Format("Do you realy want to delete the '{0} to {1}' trip?", tripToDelete.From, tripToDelete.To))
            .SetPositiveButton("Yes", (senderAlert, args) => {
                // If the position of the trip to delete is greater than the currently selected trip then just delete it
                if (e.TripPosition > TrainTrips.Selected)
                {
                    // Delete the trip
                    TrainTrips.DeleteTrip(e.TripPosition);

                    // Refresh the spinner adapter
                    spinnerAdapter.ReloadSpinner(TrainTrips.TripStrings());
                }
                // If the position of the trip to delete is less than the currently selected trip the delete it and reduce the
                // index of the selected trip
                else if (e.TripPosition < TrainTrips.Selected)
                {
                    // Delete the trip
                    TrainTrips.DeleteTrip(e.TripPosition);

                    // Refresh the spinner adapter
                    spinnerAdapter.ReloadSpinner(TrainTrips.TripStrings());

                    // Select the previous trip
                    tripSpinner.SetSelection(TrainTrips.Selected - 1);
                }
                // If the selected trip is being deleted then either keep the selected index the same and refresh it, or if
                // the end of the list has been reached then reduce the selected trip index. If there are no items left then set the index to -1
                // and make sure that the results are cleared
                else
                {
                    // Delete the trip
                    TrainTrips.DeleteTrip(e.TripPosition);

                    // Refresh the spinner adapter
                    spinnerAdapter.ReloadSpinner(TrainTrips.TripStrings());

                    if (TrainTrips.Selected >= TrainTrips.Trips.Count)
                    {
                        if (TrainTrips.Selected > 0)
                        {
                            // Select the previous trip
                            tripSpinner.SetSelection(TrainTrips.Selected - 1);
                        }
                        else
                        {
                            // Clear the selection. This will not cause the selected event to be called so clear the journey details explicitly
                            tripSpinner.SetSelection(-1);

                            TrainTrips.Selected = -1;

                            // Clear the currently displayed data
                            trainJourneyRetrieval.ClearJourneys();

                            // Reset the update time
                            updateTimer.ResetTimer();
                        }
                    }
                    else
                    {
                        // Need to simulate a selection changed event
                        TripItemSelected(null, new AdapterView.ItemSelectedEventArgs(null, null, TrainTrips.Selected, 0));
                    }
                }
            })
            .SetNegativeButton("No", (EventHandler <DialogClickEventArgs>)null)
            .Create()
            .Show();
        }
示例#7
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            // Initialise the action bar
            SetSupportActionBar(FindViewById <Toolbar>(Resource.Id.toolbar));

            // Create a StorageMechanism instance
            PersistentStorage.StorageMechanism = new StorageMechanism(this);

            // Hide the progress bar
            loadingProgress            = FindViewById <ProgressBar>(Resource.Id.loadProgress);
            loadingProgress.Visibility = ViewStates.Invisible;

            // Fill the spinner control with all the available trips and set the selected trip
            tripSpinner = FindViewById <TripSpinner>(Resource.Id.spinner);

            // Create adapter to supply these strings. Use a custom layout for the selected item but the standard layout for the dropdown
            spinnerAdapter = new TripAdapter(this, Resource.Layout.spinner_item, TrainTrips.TripStrings(), tripSpinner);
            spinnerAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);

            // Link the spinner with the trip data and display the selected trip
            tripSpinner.Adapter = spinnerAdapter;
            tripSpinner.SetSelection(TrainTrips.Selected);

            // Put an empty set of results into an adapter and assign the adapter to the list view.
            journeyList    = FindViewById <ListView>(Resource.Id.journeysView);
            journeyAdapter = new TrainJourneyWrapper(this, new TrainJourney[0]);

            journeyList.Adapter = journeyAdapter;

            // Link into the adapters More Journeys button
            journeyAdapter.MoreJourneysEvent += MoreJourneysRequest;

            // Link this activity with responses from the JourneyRetrieval instance
            trainJourneyRetrieval.JourneyResponse = this;

            // Trap clicking on the manual update field
            updateText        = FindViewById <TextView>(Resource.Id.updateText);
            updateText.Click += PerformManualUpdate;

            // Create a ResultsTimer to handle updating the results 'age' message
            updateTimer = new ResultsTimer();
            updateTimer.TextChangedEvent += UpdateTextChanged;
            updateTimer.ResetTimer();

            // Get the train journeys for the current trip (if there is one )
            if (TrainTrips.Selected >= 0)
            {
                // Keep track of the selected trip details so that any changes can be validated
                selectedTrainTrip = TrainTrips.SelectedTrip;

                PrepareForRequest(true);

                // This is an synch call. It will load the results into the TrainJourneyWrapper when available
                trainJourneyRetrieval.GetJourneys(TrainTrips.SelectedTrip);
            }

            // Trap the spinner selection after the initial request
            tripSpinner.ItemSelected += TripItemSelected;

            // Trap the spinner being opened
            tripSpinner.ClickedEvent += TripSpinnerClicked;

            // Trap the trip list long click
            spinnerAdapter.LongClickEvent += TripLongClick;
        }