我的Spinner
中实施的Activity
存在问题。我相信我认为部分尚不清楚如何寻求完整的解决方案。我有以下Spinner
定义代码段:
spinner = (Spinner) findViewById(R.id.spinner1);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.regions, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
填充此Spinner
的数组位于strings.xml:
<string-array name="regions">
<item>West</item>
<item>East</item>
<item>Asia</item>
<item>Africa</item>
<item>Croatia</item>
</string-array>
现在,我执行应用程序时遇到的异常是NullPointerException
由onItemSelected
实现的Spinner
方法。这是方法体:
public void onItemSelected(AdapterView<?> parentView,View v,int position,long id) {
// TODO Auto-generated method stub
//Log.d("Position Value: ",(String.valueOf(position).toString()));
if(position != 0)
{
if(spinner.getItemAtPosition(position).toString() != null)
{
filterObject.setRegion(spinner.getItemAtPosition(position).toString());
}else{
filterObject.setRegion("Something Wrong!");
}
}
}
如果我删除了第一个检查,即位置!= 0,则应用程序在运行时立即崩溃。一旦我将代码放在这里,应用程序加载正常,当我在Spinner
中选择一个元素时,它会立即崩溃。什么可以解决这个问题?
谢谢,
错误日志:
11-30 12:00:47.915: E/AndroidRuntime(19300): FATAL EXCEPTION: main
11-30 12:00:47.915: E/AndroidRuntime(19300): java.lang.NullPointerException
11-30 12:00:47.915: E/AndroidRuntime(19300): at com.example.sketching.MainActivity.onItemSelected(MainActivity.java:69)
11-30 12:00:47.915: E/AndroidRuntime(19300): at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
11-30 12:00:47.915: E/AndroidRuntime(19300): at android.widget.AdapterView.access$200(AdapterView.java:49)
11-30 12:00:47.915: E/AndroidRuntime(19300): at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:860)
答案 0 :(得分:0)
不需要这种情况,onCreate()
本身Spinner
onItemSelected
会触发。因此,您需要Initialize
filterObject
implement
OnItemSelectedListener
Spinner
之前的{{1}}