android - onCreate(Bundle savedInstanceState) 始终为 null

标签 android android-lifecycle activity-lifecycle

我知道,之前在 stackoverflow 上有人问过这个问题,但没有一个答案对我有用。

可能值得一提:

  • 我使用带有支持包的 ActionBarSherlock。
  • 方法 onSaveInstanceState 在我按下主页按钮时被调用。 onCreate 方法总是为 Bundle savedInstanceState 提供 NULL。
  • 方法 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

最佳答案

检查您的 list 不包含 android:noHistory="true"。

我花了几个小时寻找答案,就是这么简单。

关于android - onCreate(Bundle savedInstanceState) 始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15687007/

相关文章:

android - 我可以在 React Native 中要求专门针对 iOS 的模块吗?

java - 将 Sugar ORM 与 UUID 或 Joda-Time 结合使用

android - Activity 恢复后对新副本的 Viewpager fragment 引用

Android:Activity.onPause() 之后的点击事件

android - 如何在 sharedpreferences 中保存和检索多个值?

android - 何时调用 onRestoreInstanceState?

android - 强制 Android 在方向更改时不重绘 Activity

android - FragmentManager IndexOutOfBoundsException 无法恢复 Activity 崩溃

android - Activity 开始时的动画会跳帧

android - 用 Dagger2 注入(inject) ViewModel