setOnItemSelectedListener is not working for spinner

  • Replies:0
  • Forum posts: 1

Oct 17, 2014, 6:46:07 AM via Website

I have populated items in spinner using xml file. I have used entries option. I have used the following code. In debug mode, i found that s1 is equal to null. That is why, setOnItemSelectedListener is not working when an item is selected in spinner. Toast message is not displayed. How to set s1 to a value.

public class MainActivity extends ActionBarActivity{
String[] presidents;

protected void onCreate(Bundle savedInstanceState){

    if (savedInstanceState == null) {
               .add(, new PlaceholderFragment())

    presidents = getResources().getStringArray(R.array.presidents);

    Spinner s1 = (Spinner) findViewById(;

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.presidents, android.R.layout.simple_spinner_item);

    if(s1 != null){

        s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> arg0,
                    View arg1, int arg2, long arg3)
                int index = arg0.getSelectedItemPosition();
                Toast.makeText(getBaseContext(), presidents[index], Toast.LENGTH_SHORT).show();

            public void onNothingSelected(AdapterView<?> arg0){