0

我有一个 android 应用程序,用 java 编写,其中包含一个微调器,在 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
4

2 回答 2

0

使用 aSpinnerAdapter而不是ArrayAdapter..

于 2012-08-14T14:22:15.670 回答
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>
于 2012-08-14T14:37:05.047 回答