2011-09-16 51 views
0

我的代碼是這樣獲得空指針異常android系統中共享偏好

//要保存我的表單數據

private final OnClickListener mFinishListener = new OnClickListener() { 
     public void onClick(View v) { 

     SharedPreferences.Editor editor = getPreferences(0).edit(); 

     editor.putString("txtName",mName.getText().toString()); 

     servState = 1; 
     editor.putInt("AppState", servState); 
     editor.commit(); 

     } 

//取回屬於我的表單數據

protected void onResume() { 
     super.onResume(); 

     SharedPreferences prefs = getPreferences(0); 
     int restoreServState = prefs.getInt("AppState", 0); 


     if(restoreServState == 0){ 
      setContentView(R.layout.main); 
      Button button = (Button)findViewById(R.id.btnFinish); 
      button.setOnClickListener(mFinishListener); 
     } 
     else { 

      setContentView(R.layout.pwd); 
      int selectionStart = prefs.getInt("selection-start", -1); 
      int selectionEnd = prefs.getInt("selection-end", -1); 
      if (selectionStart != -1 && selectionEnd != -1) { 
       //mSaved.setSelection(selectionStart, selectionEnd); 
      } 
     } 

    } 

我在保存上述代碼中的OnClick事件中的數據時,獲取NullPointerException。確切的線我得到的問題是

editor.putString("txtName",mName.getText().toString()); 

請建議這裏有什麼問題嗎?我是否需要更改清單文件中的任何內容以使用共享首選項?

+2

有三種不同的東西可能爲空 - 您需要通過一些調試來找出它的含義。它們是'editor','mName'和'mName.getText()'。找出哪一個是空的,並讓我們知道。 –

+0

mName不爲空我檢查了,我把一個像if(editor!= null)這樣的語句,它仍然拋出相同的,我dint把文本框爲空,所以它不能爲空。請任何其他想法? –

回答

1

可能有兩個問題,獲得此錯誤

其實活動啓動時,它調用的onCreate()第一

的onResume()是在創建活動後,調用,所以可能是你的控制時,可能沒有得到資源

1)so had setContentView(R.layout.main) in onCreate? 
2)had you initialize EditText mName=(EditText) findViewById(R.id.label);? 

檢查這個事情,可能工作

+0

http://pastebin.com/aDCxvg7R - 我把我的代碼放在這裏。我知道很少的Java。請幫忙。 –

+0

http://pastebin.com/EMWcrHZs看到我編輯過的只是替換它 –

+0

我檢查了你的代碼。但它仍然顯示相同的問題... –