我有一个用java编写的Android应用程序,其中包含一个微调器,在layout.xml中显示如下:
<Spinner
android:id="@+id/sprDeviceType"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
它在活动类中初始化如下:
public class AddDevice extends Activity
{
private Spinner deviceTypeSpinner;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add); //Set the layout
populateDeviceTypeSpinner();
}
private void populateDeviceTypeSpinner()
{
String device_type_spinner[];
device_type_spinner = new String[2];
device_type_spinner[0] = "FTP";
device_type_spinner[1] = "QAF";
deviceTypeSpinner = (Spinner) findViewById(R.id.sprDeviceType);
ArrayAdapter deviceTypeArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, device_type_spinner);
deviceTypeSpinner.setAdapter(deviceTypeArrayAdapter);
}
}
但是,当我运行程序时,它会打开活动,但是当我单击微调器来获取下拉项时,它会崩溃程序,抛出NullPointerException。
任何人都能看到我做错了什么?
LogCat显示:
08-14 14:57:02.034: D/AndroidRuntime(1612): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
08-14 14:57:02.034: D/AndroidRuntime(1612): CheckJNI is OFF
08-14 14:57:02.074: D/AndroidRuntime(1612): --- registering native functions ---
08-14 14:57:05.004: D/AndroidRuntime(1612): Shutting down VM
08-14 14:57:05.014: I/AndroidRuntime(1612): NOTE: attach of thread 'Binder Thread #3' failed
08-14 14:57:05.184: D/AndroidRuntime(1637): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<
08-14 14:57:05.184: D/AndroidRuntime(1637): CheckJNI is OFF
08-14 14:57:05.224: D/AndroidRuntime(1637): --- registering native functions ---
08-14 14:57:05.524: D/AndroidRuntime(1637): Shutting down VM
08-14 14:57:05.544: I/AndroidRuntime(1637): NOTE: attach of thread 'Binder Thread #3' failed
答案 0 :(得分:0)
使用SpinnerAdapter
代替ArrayAdapter
..
答案 1 :(得分:0)
我从使用我编程的数组改为使用保存在值xml中的数组。
private void populateDeviceTypeSpinner()
{
deviceTypeSpinner = (Spinner) findViewById(R.id.sprDeviceType);
ArrayAdapter<CharSequence> deviceTypeArrayAdapter = ArrayAdapter.createFromResource(this, R.array.deviceType, android.R.layout.simple_spinner_item);
deviceTypeArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
deviceTypeSpinner.setAdapter(deviceTypeArrayAdapter);
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="deviceType">
<item >FTP</item>
<item >QAF</item>
</string-array>
</resources>