Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment saveInstanceState is coming as null after orientation change

I have an activity with action bar tab. Each tab contain a fragment. Now when I rotate my device, bundle in my corresponding fragment is coming as null. This is taken care when I using device post android 3.2, but it is happening when device is Andoird3.0. I am having a headache after working on this issue. I crossed check various link on SO, but no help. Although I have given enough details, still will provide some code snippet as at various cases user ask for code snippet.

In my fragment class I am storing this value

 @Override
    public void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putBoolean("textboxVisible", true);
    }

this is storing one boolean variable which it retrived as below.

/**
 * Function called after activity is created. Use this
 * method to restore the previous state of the fragment
 */
     @Override
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) 
    {
        //restore the state of the text box
        boolean textboxVisible = savedInstanceState.getBoolean("textboxVisible");
        if (textboxVisible) 
        {
            //do some stuff
        }                   
    }
}

but after rotation savedInstanceState is coming as null. I don't what is going wrong. I have read in some document that below 3.2 the onCreateView() of fragment is not called with bundle value. But to deal with this. Any help will be appreciated.

like image 778
random4Infinity Avatar asked Dec 11 '12 07:12

random4Infinity


Video Answer


2 Answers

if you use setRetainInstance(true) the savedInstance bundle is always gonna be null after orientation changed. SO you cannot really save something with it, but what you can do if you need to save something, is to put it in a data member of the fragment, because setRetainInstance(true) preserves the fragment and doesn't destroy it, so after the device was rotated you gonna have the same values.

like image 51
Radu Comaneci Avatar answered Oct 11 '22 05:10

Radu Comaneci


Try to get the savedInstanceState in onCreate of the Fragment. Like

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);

        if (savedInstanceState != null) {
            // IT MUST NOT BE NULL HERE
        }
    }

Please try... i hope it will work

like image 31
Faizan Avatar answered Oct 11 '22 05:10

Faizan