Teovald
Teovald

Reputation: 4389

Fragment with retainInstance = true, but onCreate is called

I have a layout containing a fragment :

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <fragment
        android:id="@+id/ID"
        class="com.teovald.app.MyFragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

</FrameLayout>

I set this use setRetainInstance(true) in this fragment onCreate method :

 public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setRetainInstance(true);
    ....}

And finally I recuperate a reference to this fragment in its activity onCreate as well :

 public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    FragmentManager fragmentManager = getSupportFragmentManager();
    mFragment = (MyFragment)  fragmentManager.findFragmentById(R.id.ID);    
    ...
}

However, each time I rotate my device, onCreate of the activity is called, then onCreate of the fragment is called as well ! Since I seted up setRetainInstance to true, it should not happen. Is there a reason for this behavior ?

Upvotes: 1

Views: 1129

Answers (1)

Jerzy Kiler
Jerzy Kiler

Reputation: 3655

I had this issue recently and was fighting with it for a couple of hours until I discovered that in the code (that I copied from some third party library) of the Activity which contains the retained non-ui-fragment in onSaveInstanceState there was no call to super.onSaveInstanceState()

It was like that:

@Override
protected void onSaveInstanceState(Bundle outState) {
    // Save the mapview state in a separate bundle parameter
    final Bundle mapviewState = new Bundle();
    mMapFragment.onSaveInstanceState(mapviewState);
    outState.putBundle(BUNDLE_STATE_MAPVIEW, mapviewState);
}

So I added the missing call to be like:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // Save the mapview state in a separate bundle parameter
    final Bundle mapviewState = new Bundle();
    mMapFragment.onSaveInstanceState(mapviewState);
    outState.putBundle(BUNDLE_STATE_MAPVIEW, mapviewState);
}

And now onCreate() is not called twice in the retained fragment.

I hope this will help somebody :)

Upvotes: 1

Related Questions