Java – “Don’t Keep Activities” opened View with ID not found

“Don’t Keep Activities” opened View with ID not found… here is a solution to the problem.

“Don’t Keep Activities” opened View with ID not found

My app crashes intermittently after inactivity. So I guess I didn’t store things properly. I turned on “Do not keep activities” for troubleshooting, but now my app crashes everywhere.

Stack trace: https://gist.github.com/hanleyhansen/6d41fee54b1e129b7922
Here is the missing layout: https://gist.github.com/hanleyhansen/73ace0c99ae675023e0f

Solution

I think you may be experiencing symptoms of Issue 19917. This bug exists in version 3.2 and later and was only recently fixed (4.2). The same fix hasn’t made it into the support library yet.

See comment 28 A real fix: you’ll want to edit your support library and recompile. Edit the v4/java/android/support/v4/app/FragmentManager .java

Bundle saveFragmentBasicState(Fragment f) {
    Bundle result = null;

if (mStateBundle == null) {
        mStateBundle = new Bundle();
    }
    f.onSaveInstanceState(mStateBundle);
    if (!mStateBundle.isEmpty()) {
        result = mStateBundle;
        mStateBundle = null;
    }

if (f.mView != null) {
        saveFragmentViewState(f);
    }
    if (f.mSavedViewState != null) {
        if (result == null) {
            result = new Bundle();
        }
        result.putSparseParcelableArray(
                FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);
    }
    if (!f.mUserVisibleHint) {
         Only add this if it's not the default value
         @@@ BUG, result may not have been created, can be null!
        if (result == null) {
            result = new Bundle();
        }
        result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint);
    }

return result;
}

If you feel that you are not up to the task, and want to wait for Google to fix the support library
This is another workaround
Comment 8For fixes, you can apply it to all fragments

    @Override
    public void onSaveInstanceState(Bundle outState) {
        first saving my state, so the bundle wont be empty.
        http://code.google.com/p/android/issues/detail?id=19917
        outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE");
        super.onSaveInstanceState(outState);
    }

I also came across transaction.commitAllowingStateLoss(); as a “fix” for this instead of transaction.commit();

Some other relevant background information and workarounds I’ve found to help me with fragment issues, especially when nesting them

Related Problems and Solutions