SavedInstanceState is null in onCreateView for Fragment when returning from another activity and not when returning from other apps

UPDATE

The only workaround I could find was creating a variable static

and saving the state there. This is not a good solution, but it works.

I tried to save state in Activity, but Activity was onRestoreInstanceState

never called.


I am not using setRetainInstance()

.

When on snippet and I rotate the device or multitask to another app and then return, savedInstanceState

it doesn't matter in onCreateView

. BUT when I stay in the app and click on an item in a fragment ListView

and use an intent to show another activity and then click the back button to go back to the original activity (which is showing my fragment) thennull! Why?

NOTE: the answer is in this How can I maintain the state of the fragment when added to the back stack? did not work. My instance variables are in their default state when I return from another activity.

//It is a android.support.v4.app.Fragment;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    //Only shows null when returning from another Activity IN this app
    Log.v(getClass().getSimpleName(), "NULL?" + savedInstanceState);

    return createMyView();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    //Save some value (It is NOT null here)
    outState.putInt("TestKey", "saved_key" );

    //Save the state
    super.onSaveInstanceState(outState);

    //This is never null, so should be ok
    Log.v(getClass().getSimpleName(), "Outstate : " + outState);
}

@Override
public void onViewStateRestored(Bundle savedInstanceState) {
    //SavedInstanceState is NULL here too (when returning from within same app)!
    super.onViewStateRestored(savedInstanceState);
}

      

Why is it null when returning from another activity, but not when returning from other applications?

+3


source to share





All Articles