11
votes

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.

2
Are you using android:configChanges ?? - Faizan
Also, Have you tried setRetainInstance(true); ???? - Faizan
Basically I am using two different layout for landscape and portrait mode. So can't use android:configChange. And setRetainInstance(true), i ahve not used in current scenario but I have used it earlier, it was not working. Still will give a try in current scenario also - random4Infinity
@Faizan setRetainInstance(true) is of no help. Its not working:( - random4Infinity

2 Answers

4
votes

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.

3
votes

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