issue with spinner

alim.2888alim.2888 USMember ✭✭

I want to select an item in the spinner and then write it in a TextView (inside a button click ) but I have an error. http://uupload.ir/files/bo3n_capture.jpg
help me
my code:

`using Android.App;
using Android.Widget;
using Android.OS;
using System;
using System.Collections.Generic;

namespace plctowi
{
[Activity(Label = "plctowi", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{

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

        // Set our view from the "main" layout resource
         SetContentView (Resource.Layout.Main);
        Button btni = FindViewById<Button>(Resource.Id.button2);
        btni.Click += btn2click;

        Spinner spinner = FindViewById<Spinner>(Resource.Id.spinner);
        List<string> dataList = new List<string>();

        dataList.Add("1");
        dataList.Add("2");
        dataList.Add("3");
        var ArrayAdapter1 = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, dataList);
        spinner.Adapter = ArrayAdapter1

    }

    public void btn2click(object sender, EventArgs e)
    {

        var itemSelected = (string)spinner.SelectedItem;

        if (itemSelected == "db"  )
        {
          TextView mytext = FindViewById<TextView>(Resource.Id.textView1);
           mytext.Text = "Clicked 1";

        }
        else if (itemSelected == "2")
        {
            TextView mytext = FindViewById<TextView>(Resource.Id.textView1);
            mytext.Text = "Clicked 2";

        }
        else if (itemSelected == "3")
        {
            TextView mytext = FindViewById<TextView>(Resource.Id.textView1);
            mytext.Text = "Clicked 3";
        }


    }



}

}

`

Answers

  • DhilluDhillu INMember ✭✭✭

    You have two Spinners in your code.
    One ( declared at class level ), will always be null, since no where in your code you are instantiating it.
    Another one ( at method level ) in your OnCreate , you are attaching the Adapter to this.

    But on your btn2click, you are trying to get the SelectedItem from the one, which was not instantiated.

    Change

    Spinner spinner = FindViewById<Spinner>(Resource.Id.spinner);

    to

    spinner = FindViewById<Spinner>(Resource.Id.spinner);

Sign In or Register to comment.