spinner.setSelection帮助

时间:2011-06-11 21:27:22

标签: android nullpointerexception spinner

我正在尝试加载我的首选项并更新微调器以显示以前保存的值。我以前从未使用过spinner.setSelection并且一直在使用nullpointerexceptions。

String[] timeItems = new String[] {"After 2 minutes", "After 5 minutes", "Never"};
ArrayAdapter<String> adapter;
Spinner screenSpinner;

的onCreate():

Spinner screenSpinner = (Spinner)findViewById(R.id.spinner_screen);
        screenSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, timeItems);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        screenSpinner.setAdapter(adapter);

loadPrefs()

    //load the preferences
...
    //then update the selection in the spinner    
    if (mScreenTimer == SCREEN_TIMER_2MINUTES) {
                    int tmp_index = adapter.getPosition("After 2 minutes");
                    screenSpinner.setSelection(tmp_index,true);
                } else if (mScreenTimer == SCREEN_TIMER_5MINUTES) {
                    int tmp_index = adapter.getPosition("After 5 minutes");
                    screenSpinner.setSelection(tmp_index,true);
                } else if (mScreenTimer == SCREEN_TIMER_NEVER) {
                    int tmp_index = adapter.getPosition("Never");
                    screenSpinner.setSelection(tmp_index,true);
                }

我在screenSpinner.setSelection上获得了NullPointerExecption(tmp_index,true)

1 个答案:

答案 0 :(得分:1)

尝试在设置适配器

后设置选择