0

我是 android/java 新手,所以请多多包涵。我的代码之前运行良好,但自从我添加了 for() 循环后,我就收到了 NullPointerException。有任何想法吗?

public class PreferencesActivity extends Activity {

SharedPreferences settings;
SharedPreferences.Editor editor;
static CheckBox box, box2;

private final static CheckBox[] boxes={box, box2};
private final static String[] checkValues={"checked1", "checked2"};


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    box=(CheckBox)findViewById(R.id.checkBox);
    box2=(CheckBox)findViewById(R.id.checkBox2);

    settings= getSharedPreferences("MyBoxes", 0);
    editor = settings.edit();

    if(settings != null){

    for(int i =0;i<boxes.length; i++)
        boxes[i].setChecked(settings.getBoolean(checkValues[i], false));   
    }

}

@Override
protected void onStop(){
   super.onStop();

   for(int i = 0; i <boxes.length; i++){           
   boolean checkBoxValue = boxes[i].isChecked();        
   editor.putBoolean(checkValues[i], checkBoxValue);
   editor.commit();       
   }

    }
}
4

2 回答 2

1

您初始化 和 的值boxbox2因为null这是未明确分配时的默认值)。Checkbox然后在创建数组时使用这些值boxes。因此,boxes有两个空值。然后重新分配 和 的boxbox2boxes请注意,这对数组中的值没有影响。因此,当您尝试访问数组中的值时,您会得到一个NullPointerException.

在为和分配值boxes 设置其中的值。boxbox2

于 2012-05-15T22:35:03.140 回答
0

这是固定代码。希望它有所帮助:

public class PreferencesActivity extends Activity {

    SharedPreferences settings;
    SharedPreferences.Editor editor;
    static CheckBox box, box2; // box and box2 are null when class is loaded to DalvikVM

    private final static CheckBox[] boxes={null, null};
    private final static String[] checkValues={"checked1", "checked2"};


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        box=(CheckBox)findViewById(R.id.checkBox);
        box2=(CheckBox)findViewById(R.id.checkBox2);

        // assign CheckBox instances to boxes array
        boxes[0] = box;
        boxes[1] = box2;

        settings= getSharedPreferences("MyBoxes", 0);
        editor = settings.edit();

        if(settings != null){

        for(int i =0;i<boxes.length; i++)
            boxes[i].setChecked(settings.getBoolean(checkValues[i], false));   
        }

    }

    @Override
    protected void onStop() {
        super.onStop();

        for(int i = 0; i <boxes.length; i++){           
            boolean checkBoxValue = boxes[i].isChecked();        
            editor.putBoolean(checkValues[i], checkBoxValue);
            editor.commit();       
        }
    }
}
于 2012-05-16T03:46:28.557 回答