Search code examples
androidfragmentstatepageradapter

Implementing onSavedInstanceState stops FragmentStatePagerAdapter working


In my activity, I had found I needed to store state for one of my tabs in a tabbed view. This was the result of a search bar, and I needed an Activity to receive and store the data.

Although my application was working before hand, when I implemented in my Activity

public void onSaveInstanceState( Bundle outState ){
    ArrayList<SearchData.SearchDataSerial> sdSerial = new ArrayList<SearchData.SearchDataSerial>();
    int i;
    for( i = 0; i < mSearchData.size() ; i++ ){
        SearchData item = mSearchData.get(i);
        SearchData.SearchDataSerial elem = new SearchData.SearchDataSerial( item );
        sdSerial.add( elem );
    }
    outState.putParcelableArrayList( "searchterms", sdSerial );


    Log.d( TAG, "OnSaveInstanceState" );
}

It broke the persistence of all the other fragments in the tabs.

Also if in onCreate for the activity, if I had to change my code to this to keep the pages loading.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /* ... not relevant */
    // if( savedInstanceState == null ) { /* had to comment out this line */
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        SlidingTabsBasicFragment fragment = new SlidingTabsBasicFragment();
        transaction.replace(R.id.tabbed_layout_main, fragment);
        transaction.commit();
    //} /* had to comment out this line */
    if (savedInstanceState != null) {
        loadSavedData( savedInstanceState );
    }

    setupActionBar();
}

Solution

  • As the docs say:

    Caution: You must always call the superclass implementation of onSaveInstanceState() so the default implementation can save the state of the view hierarchy.

    So the correct code should look like...

    @Override
    public void onSaveInstanceState( Bundle outState ){
        super.onSaveInstanceState( outState ); /* Needs to be here for framework to work */
        ArrayList<SearchData.SearchDataSerial> sdSerial = new ArrayList<SearchData.SearchDataSerial>();
        int i;
        for( i = 0; i < mSearchData.size() ; i++ ){
            SearchData item = mSearchData.get(i);
            SearchData.SearchDataSerial elem = new SearchData.SearchDataSerial( item );
            sdSerial.add( elem );
        }
        outState.putParcelableArrayList( "searchterms", sdSerial );
    
    
    Log.d( TAG, "OnSaveInstanceState" );
    }