2012-06-23 97 views
0
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main2); 
    savedInstanceState.putString("foo", "bar"); 
} 

@Override 
public void onRestoreInstanceState(Bundle savedInstanceState) { 
    super.onRestoreInstanceState(savedInstanceState); 

    String myString = savedInstanceState.getString("foo"); 

    Log.i("debug", "saved data: " + myString); 
} 

我試着在活動中保留一些價值,但我收到以下錯誤:06-23 23:09:44.038: E/AndroidRuntime(17584): java.lang.RuntimeException: Unable to start activity ComponentInfo{se.johanberntsson.activitytest/se.johanberntsson.activitytest.TestActivity}: java.lang.NullPointerException獲取savedInstanceState值,NullPointerException異常

我錯過了什麼嗎?在savedInstanceState捆綁節約值作爲感謝

+0

試井如果'savedInstanceState',看它是否是'之前調用null''的getString(...)'將是一個良好的開端。你如何努力「保留一些價值」?也許使用'SharedPreferences'可能是一個更好的選擇。 – Squonk

回答

2

覆蓋onSaveInstanceState

public String strfoo=""; 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main2); 
      //comment this line you only fatch values from savedInstanceState 
      String myString = savedInstanceState.getString("foo"); 
      Log.i("debug", "saved data: " + myString); 
      // savedInstanceState.putString("foo", "bar"); 
      strfoo="bar"; set value here 
     } 

     @Override 
     public void onRestoreInstanceState(Bundle savedInstanceState) { 
      super.onRestoreInstanceState(savedInstanceState); 
      String myString = savedInstanceState.getString("foo"); 
      Log.i("debug", "saved data: " + myString); 
     } 

     @Override 

     public void onSaveInstanceState(Bundle savedInstanceState) { 
     savedInstanceState.putString("foo", strfoo); 
     super.onSaveInstanceState(savedInstanceState); 

     } 
+0

謝謝!但是,當我開始我的新活動 - >按「返回」 - >再次啓動相同的活動,我沒有看到我的日誌中的「酒吧」。當時不應該調用'onRestoreInstanceState'? – Johan

+0

onRestoreInstanceState僅在任何配置時調用。發生變化。 –

+0

但我想當你按下返回按鈕onRestoreInstanceState和onSaveInstanceState沒有調用。所以改變你的邏輯和使用sharedpreferce存儲值,當用戶按下按鈕時,通過覆蓋onKeyDown或onBackPressed –