2012-05-15 74 views
0

我是新來的android/java,請耐心等待。我的代碼工作得很好,但自從我添加for()循環以來,我一直在收到一個NullPointerException。有任何想法嗎?Android開發者:java.lang.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();  
    } 

    } 
} 
+1

logcat的痕跡請,我認爲這箱子是空您的發言 – moujib

回答

1

你初始化的boxbox2值是null(因爲這是他們沒有明確指定的默認值)。這些值將在創建Checkbox陣列boxes時使用。因此,boxes有兩個空值。然後您重新指定boxbox2的值。請注意,這對boxes陣列中的值沒有影響。因此,當你試圖訪問數組中的值時,你會得到一個NullPointerException

集中boxes後,您已經爲boxbox2賦值。

+0

你能給我將如何做到這一點的例子嗎? – drew

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