Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FragmentManager.getFragment() NullPointerException

I am using support library v4 and failing to save fragment's state.

@Override
protected void onSaveInstanceState(Bundle outState)
{
    ...
    if(mFragment != null)
        getSupportFragmentManager().putFragment(outState, "frag", mFragment);
    ...
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
    ...
    if(savedInstanceState != null)
    {
        //Here I get NullPointerException
        getSupportFragmentManager().getFragment(savedInstanceState, "frag");
    }
    ...
}

When I call getFragment() NullPointerException is thrown (savedInstanceState contains entry with "frag").

Here is the part of logcat output:

04-18 00:10:56.719: E/AndroidRuntime(14644): Caused by: java.lang.NullPointerException
04-18 00:10:56.719: E/AndroidRuntime(14644):    at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:569)

Also I have tried to call getFragments() which returns null. That appears to me strange.

I will appreciate any help!


Solution:

I forgot to use super.onSaveInstanceState(outState); inside onCreate method.

like image 676
Tzoiker Avatar asked Oct 01 '22 00:10

Tzoiker


1 Answers

Thanks to @Fllo. The problem was that I forgot to call onSaveInstanceState() of parent activity.

@Override
protected void onSaveInstanceState(Bundle outState)
{
    //Added this and the problem was solved
    super.onSaveInstanceState(outState);
    ...
}
like image 182
Tzoiker Avatar answered Oct 13 '22 11:10

Tzoiker