Android Begineer:java.lang.NullPointerException

时间:2012-05-15 22:28:32

标签: java android eclipse android-layout android-intent

我是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();       
   }

    }
}

2 个答案:

答案 0 :(得分:1)

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

在之后设置boxes 中的值,并为boxbox2分配值。

答案 1 :(得分: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();       
        }
    }
}