以下代码抛出 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);
}
}
由于explanation = (TextView) findViewById(R.id.picker_explanation_text);
方法中的onItemSelected(...)
引发了它,但我不明白为什么。毕竟,它是在onCreate(...)
方法中工作的。
答案 0 :(得分:1)
而不是
spinner.setOnItemSelectedListener(new test());
使用
spinner.setOnItemSelectedListener(this);
您希望将您的真实活动用作目标;你正在创建一个永远不会被上下文初始化的新对象,因此当它被调用时会崩溃。