简体   繁体   中英

spinner.setSelection help

I'm trying to load my preferences and update a spinner to show the previously saved value. I've never used spinner.setSelection before and keep getting 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);
                }

I get the NullPointerExecption on screenSpinner.setSelection(tmp_index, true)

Try setting the selection after setting the adapter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM