I am new to android/java so please bear with me. My code was working fine earlier, but ever since I added the for() loops, I have been getting a NullPointerException. Any Ideas?
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();
}
}
}
You initialise the values of
boxandbox2to benull(as this is the default value when they are not assigned explicitly). These values are then used when creating yourCheckboxarrayboxes. Thus,boxeshas two null values. You then reassign the values ofboxandbox2. Note that this has no effect on the values within theboxesarray. Thus when you attempt to access the values within the array you get aNullPointerException.Set the values within
boxesafter you have assigned values forboxandbox2.