Search code examples
androidandroid-fragmentsforceclose

null pointer exception on save instance


I am getting a force close reported from my app users that gives this error:

java.lang.NullPointerException
       at com.beerportfolio.beerportfoliopro.MainDrawer2.onSaveInstanceState(MainDrawer2.java:160)
       at android.app.Activity.performSaveInstanceState(Activity.java)
       at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java)
       at android.app.ActivityThread.performStopActivityInner(ActivityThread.java)
       at android.app.ActivityThread.handleStopActivity(ActivityThread.java)
       at android.app.ActivityThread.access$1100(ActivityThread.java)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
       at android.os.Handler.dispatchMessage(Handler.java)
       at android.os.Looper.loop(Looper.java)
       at android.app.ActivityThread.main(ActivityThread.java)
       at java.lang.reflect.Method.invokeNative(Method.java)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
       at dalvik.system.NativeStart.main(NativeStart.java)

Line 160 is this:

outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());

which come from this method:

@Override
    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
    }

should I just use an if statement to check if either STATE_CURRENT_NAV or mCurrentNavItem.ordinal() are NULL and if they are then not execute the outState.putInt?


Solution

  • outState is contractually not null ergo your Nav Item must be null. Either null check before attempting to save or init the variable so it can not be null at the time of saving state.

    onSaveInstanceState(Bundle)