following code is throwing a NullPointerException:
public class test extends Activity implements OnItemSelectedListener {
private TextView explanation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.psqlpicker);
explanation = (TextView) findViewById(R.id.picker_explanation_text);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.picker_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener(new test());
spinner.setAdapter(adapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
explanation = (TextView) findViewById(R.id.picker_explanation_text);
}
}
It is thrown because of explanation = (TextView) findViewById(R.id.picker_explanation_text);
in the onItemSelected(...)
method, but I have no idea why. It is, after all, worki开发者_开发百科ng in the onCreate(...)
method.
Instead of
spinner.setOnItemSelectedListener(new test());
use
spinner.setOnItemSelectedListener(this);
You want to use your real activity as the target; you are creating a new object that is never initialized with a context so when it is called it crashes.
精彩评论