Search code examples
androidspinner

Spinner is not working in android


Spinner is not working. Here is my code:

public class second extends Activity{   
    Spinner spin;
    String[] str;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);        
        spin = (Spinner) findViewById(R.id.spin);
        str = new String[] {"bike","car"};      
        spin.setAdapter(new ArrayAdapter<CharSequence>(this, android.R.layout.simple_dropdown_item_1line, str));    

        spin.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> adapter, View view, int pos,
                long id) {
            // TODO Auto-generated method stub

            String data= spin.getItemAtPosition(pos).toString();
            Toast.makeText(second.this, data, Toast.LENGTH_SHORT).show();
               }    
        });
    }
}

Solution

  • The only mistake you made is you have set different event listener..

    The Listener OnItemClickListener is for ListView..

    For Spinner you have to set OnItemSelectedListener ..

    Try replacing OnItemClickListener to setOnItemSelectedListener like :

    spin.setOnItemSelectedListener (new OnItemSelectedListener() {
    
        public void onItemClick(AdapterView<?> adapter, View view, int pos,
                long id) {
            // TODO Auto-generated method stub
    
            String data= spin.getItemAtPosition(pos).toString();
            Toast.makeText(second.this, data, Toast.LENGTH_SHORT).show();
        }
    
    });