Returning more than just the selection with a spinner

GregoryHewittGregoryHewitt USMember
edited November 2016 in Xamarin.Android

Hi Everybody,

Very new to C# and Xamarin (I'm a MATLAB/Fortran/Python guy), but I've bootstrapped an app and a SQL database from zero experience pretty quickly thanks to good documentation and ye olde Google.

Here's my question:

I've got a spinner with some code like this:

Spinner AbilitySp = FindViewById<Spinner>(Resource.Id.AbilityClassSpinner);
var abilityadapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem);
AbilitySp.Adapter = abilityadapter;

abilityadapter.Add("Select Class");
abilityadapter.Add("AA - Pro");
abilityadapter.Add("A - Expert");
abilityadapter.Add("B - Amature");
abilityadapter.Add("C - Novice");

Now, when the user selects the spinner

AbilitySp.ItemSelected += spinner_ItemSelected;

We go into the following function:

    public void spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
    {
        Spinner spinner = (Spinner)sender;

        string AbilityDB = string.Format("{0}",spinner.GetItemAtPosition (e.Position));
    }

My goal is to then return the string AbilityDB back to the main code, as I use it later to do a SQL database query. Because I'm a 100% newbie in C#, I don't know how to handle this. My gut tells me to set some:

string AbilityDB = spinner_ItemSelected in the main code, but that ignores the event handler that recognizes the selection.

Please advise, and thank you!

Answers

  • JeremyKolbJeremyKolb USMember ✭✭✭

    Event handlers (ie callbacks) aren't synchronous in that way and you don't really have anything that can be considered a 'main loop'.

    I think you need to do something like: make AbilityDB a member variable in your Activity or Fragment:

    public class MySillyActivity : Activity
    {
        string _abilityDB;
    
        // ...
    
        public void spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
        {
            Spinner spinner = (Spinner)sender;
    
            // Write the selected item to _abilityDB
            _abilityDB = string.Format("{0}",spinner.GetItemAtPosition (e.Position));
        }
    
    // ... Somewhere else ...
       public void UseIt()
        {
            Android.Debug.Log("The ability! " + _abilityDB);
        }
    }
    
    
    
Sign In or Register to comment.