KRISHNA SARANU
- Forum posts: 1
Oct 17, 2014, 6:46:07 AM via Website
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;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
presidents = getResources().getStringArray(R.array.presidents);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.presidents, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
if(s1 != null){
s1.setAdapter(adapter);
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){
}
});
}
}
Recommended editorial content
With your consent, external content is loaded here.
By clicking on the button above, you agree that external content may be displayed to you. Personal data may be transmitted to third-party providers in the process. You can find more information about this in our Privacy Policy.