我是 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();
}
}
}
最佳答案
您将 box
和 box2
的值初始化为 null
(因为这是未显式分配时的默认值)。然后在创建 Checkbox
数组 boxes
时使用这些值。因此,boxes
有两个空值。然后重新分配 box
和 box2
的值。请注意,这对 boxes
数组中的值没有影响。因此,当您尝试访问数组中的值时,您会收到 NullPointerException
。
在为 box
和 box2
分配值后,在 boxes
中设置值。
关于java - Android 初学者 : java. lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10609689/