Forum Xamarin.Android

Spinner Control - Get ID and Text on Selection

astahirastahir USMember ✭✭

Hi folks,

I have started exploring the Spinner control just now. I have pretty much achieved what I wanted but only the last step is missing. Here is what I have done so far.

I have a very simple class for this example:

    [Serializable]
    public class Merchant
    {
        public Int64 MerchantId { get; set; }
        public String ShopName { get; set; }

        public override string ToString()
        {
            return ShopName;
        }
    }

Here is the axml where I placed the Spinner:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="1280dip"
    android:layout_height="800dip">
    <TextView
        android:text="Select a merchant:"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lblSelect"
        android:layout_marginLeft="30dip"
        android:layout_marginTop="30dip"
        android:textSize="42dip" />
    <Spinner
        android:id="@+id/spinMerchant"
        android:layout_width="1000dip"
        android:layout_height="wrap_content"
        android:layout_below="@id/lblSelect"
        android:prompt="@string/spinner_prompt"
        android:layout_centerHorizontal="true"
        android:minHeight="20dip" />
</RelativeLayout>

And my code is:

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Create your application here
            this.SetContentView(Resource.Layout.MerchantSelect);

            List<Merchant> lstMerchant = new List<Merchant> ();
            lstMerchant.Add (new Merchant() { ShopName = "First Shop", MerchantId = 11 });
            lstMerchant.Add (new Merchant() { ShopName = "Second Shop", MerchantId = 12 });

            Spinner spinner = this.FindViewById<Spinner>(Resource.Id.spinMerchant);
            ArrayAdapter adapter = new ArrayAdapter (this, Android.Resource.Layout.SimpleSpinnerItem, lstMerchant);
            spinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs> (spinner_ItemSelected);

            spinner.Adapter = adapter;
        }

        private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
        {
            Spinner spinner = (Spinner)sender;
            //Merchant merch = (Merchant)spinner.SelectedItem;
            string toast = string.Format ("Selected text is {0}", spinner.GetItemAtPosition (e.Position));
            Toast.MakeText (this, toast, ToastLength.Long).Show ();
        }

I want to get the selected text as well as the ID behind it as soon as the selection is made. I get the text by spinner.GetItemAtPosition (e.Position) but I can't seem to find anything that can give me the ID. If I try to do Merchant merch = (Merchant)spinner.SelectedItem; I get an exception: Cannot convert type 'Java.Lang.Object' to 'Merchant'.

Please let me know how it can be achieved.

Thanks.

Posts

  • TonciKucicTonciKucic HRMember

    Hi @astahir,

    You can tray this dirty trick for Id column:

    [Serializable]
    public class Merchant
    {
        public Int64 MerchantId { get; set; }
        public String ShopName { get; set; }
    
        public override string ToString()
        {
            return ShopName;
        }
    

    public override string GetHashValue()
    {
    return MerchantId;
    }
    }

  • TonciKucicTonciKucic HRMember

    Hi

    Nice, thanks for sharing.

  • ManInTheLoftManInTheLoft GBBeta, University ✭✭
    edited August 2014

    Ahmed

    I've been after a solution for populating and using spinners with databases. So useful, thanks.

    CR

  • astahirastahir USMember ✭✭

    CR, I'm glad it helped.

  • VAnjaneyuluVAnjaneyulu USMember
    edited December 2015

    @astahir said:
    Hi Tonci,

    Thanks for your response. However, I had already done this and this is how I did it. I defined a class-level list that I used to bind my spinner with:

    List<MerchantForWebService> lstMerchant = null;

    In my spinner.ItemSelected event, I got the merchantId like:

    merchantId = this.lstMerchant.ElementAt (e.Position).MerchantId;

    Ahmed

    Hi @astahir,

    please can u share code how you got that ID and Value.

    Thanks
    Anjaneyulu

  • astahirastahir USMember ✭✭

    @VAnjaneyulu - I don't know which code are you talking about because all the relevant code is already there and I believe it has helped others. So I can safely say that I haven't missed anything important .

  • the same problem is with me.. im using textview in spinner list.. so i want to send data from selected textview to webservice

  • im using adapter class to show data in spinners

  • SanjayTejaniSanjayTejani USMember ✭✭✭

    @astahir

    Thanks for your response.

    This one is working for me.
    this.lstMerchant.ElementAt (e.Position).MerchantId;

  • shafickshafick BRMember

    Great help. Thankyou.
    Working for me with this structure:
    string EmpregadoVerificado = string.Format("{0}", listaEmpregados.ElementAt(spnEMP.SelectedItemPosition).nome);

  • How can Get Values in Spinner from Dataset Webservices.?

  • AzwarNazzAzwarNazz USMember

    @astahir perfect

  • DimChrisDimChris USMember ✭✭✭✭

    I'm just using this

        Spinner spinner= FindViewById<Spinner>(Resource.Id.spinner1);
        String spinnerText;
        spinnerText = spinner.SelectedItem.ToString();
    
         Toast.MakeText(this, spinnerText , ToastLength.Short).Show();
    
  • LearnEverythingLearnEverything USMember ✭✭✭

    Prevent Spinner ItemSelected event fire multiple times.

    this.SpinnerTheme.ItemSelected += (sender, e) =>
                  {
                      var selected = list.ElementAt(e.Position);
                      if (selected != null)
                      {
                          if (onTouch)
                          {
                              Preferences.Set(ThemeHelper.AccentKey, selected.Value);
                              ThemeHelper.Current.RaiseEvent(selected.Value);
                              onTouch = false;
                          }
    
                      }
    
    
                  };
                this.SpinnerTheme.Touch += (s,e)=>
                {
                    onTouch = true;
                };
    
Sign In or Register to comment.