I am trying to display a Spinner list for user to select, then take the selection to bind to another array. The user-selected value surfaceCode is saved for later use. The Spinner array R.array.surface_option and the array to bind R.array.surface_code are aligned and saved in xml.
This is my code…
spinnerSurface = (Spinner) findViewById(R.id.spinnerSurface);
ArrayAdapter<CharSequence> adapterSurface = ArrayAdapter.createFromResource(this, R.array.surface_option, android.R.layout.simple_spinner_item);
adapterSurface.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSurface.setAdapter(adapterSurface);
spinnerSurface.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
TextView tx = (TextView)v;
Log.i("\n\nid",String.valueOf(tx.getText()));
String surfaceCode = getResources().getStringArray(R.array.surface_code)[spinnerSurface.getSelectedItemPosition()];
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Log.d("code outside", surfaceCode.trim() + " is equal to SW: " + surfaceCode.trim().equals("SW"));
The surfaceCode comes out as error process stopped unexpectedly, probably because it returns null. What’s wrong with my code?
surfaceCode can be null in the last code line because the code in the anonymous listener is only executed when the selection is made.
This would cause a NullPointerException in the last line.
Even if onItemSelected() is called, it will not set the member surfaceCode because you have declared a local variable of the same name that is shadowing it.
You should remove the “String ” before the surfaceCode and put the log statement inside onItemSelected().