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 o开发者_JS百科nItemClick(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();
}
});
}
}
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();
}
});
The problem is here,
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();
}
});
Try replacing it as follows,
spin.OnItemSelectedListener (new OnItemSelectListener() {
public void onItemSelect(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();
}
});
Here is the problem in your oncreate() method:
spin = (Spinner) findViewById(R.id.spin);
You assign the result to spinner which is a local variable/reference here. main.spinner class field is still null. This is why you have NullPointerException in calculate() method.
Replace the line above with:
this.spin = (Spinner) findViewById(R.id.spin);
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item,androidBooks);
spin.setAdapter(adapter);
Try this one
spinner = (Spinner) findViewById(R.id.spinner);
List<String> categories = new ArrayList<String>();
categories.add("--Qualification--");
categories.add("High School");
categories.add("Higher Secondary/PUC");
categories.add("Diploma");
categories.add("Degree");
categories.add("Master Degree");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.spinnertext, categories);
adapter.setDropDownViewResource(android.R.layout.select_dialog_item);
spinner.setAdapter(adapter);
Check Out on this link
精彩评论