[英]onCreate(Bundle savedInstanceState) in always null
我知道,這個問題是在stackoverflow上問過的,但是沒有一個答案對我有用。
大概值得一提:
onSaveInstanceState
方法。 onCreate
方法始終為Bundle savedInstanceState
賦予NULL。 onRestoreInstanceState
不會調用onRestoreInstanceState
方法。 (我不介意onCreate
有效;)。 super.onSaveInstanceState(outState)
放在onSaveInstanceState
的底部。 也沒有運氣。 這是代碼。 我希望有人遇到這個問題並解決了。
public class MainActivity extends SherlockFragmentActivity {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private static String STATE_TO_STORE = "state_to_store";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "onCreate: savedInstanceState = " + (savedInstanceState == null ? "NULL" : "Not NULL"));
// ... more code...
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(LOG_TAG, "onRestoreInstanceState: savedInstanceState = " + (savedInstanceState == null ? "NULL" : "Not NULL"));
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_TO_STORE, 5); // store some int
Log.d(LOG_TAG, "onSaveInstanceState bundle: " + outState.toString());
}
// ... more code ...
}
日志記錄清楚地表明正在調用onSaveInstanceState
,並且onCreate獲取savedInstanceState = NULL
。
檢查清單是否不包含android:noHistory =“ true”。
我花了幾個小時尋找答案,就是這么簡單。
就我而言,原因是特定活動在清單文件中沒有聲明主題。
要解決此問題,請打開AndroidManifest.xml,單擊“應用程序”,在“應用程序節點”中選擇崩潰的活動,然后在“屬性”的“主題”字段中添加主題。 就我而言,
@style/Theme.AppCompat.Light.DarkActionBar
但是您可以從其他活動之一復制主題。
PS:我知道這是一個老問題的答案,但是我在尋找修復程序時偶然發現了它,卻沒有找到可行的解決方案,因此這可能對其他人有所幫助。
當Activity因缺乏資源而被系統殺死時,將觸發onRestoreInstanceState(或onCreate中保存的捆綁軟件),並在您重新使用它時重新啟動。 在不通過onRestoreInstanceState的情況下,Activity可能不會被殺死(只是停止)並重新啟動。 換句話說,將始終調用onSaveInstanceState,但如果系統殺死並恢復了onRestoreInstanceState,則將調用它。 不僅停止並重新啟動,還沒有暫停並恢復,也沒有通過新的意圖啟動。
在這里查看我的解釋。 我確定它涵蓋了您的問題。
當您按下HOME按鈕時,您的活動將暫停並且不會被破壞。因此,當您從主屏幕再次啟動應用程序時,除非操作系統殺死您的應用程序以回收內存,否則不會調用onCreate。 如果希望從主屏幕啟動時重新創建活動,請在活動清單中放入以下行android:finishOnTaskLaunch="true"
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.