title: Save Current Fragment in onSaveInstanceState
body: <p>I have one Activity that launches a Fragment. I open my Navigation Drawer and go to a second Fragment in that same Activity. I rotate the device and instead of remaining on that second Fragment, I'm brought back to the first one. How can you save the current Fragment that you're on so that when the Activity is destroyed it opens the appropriate Fragment? Here is what I have tried but it's not working. This is in my Activity:</p>
  
  <pre><code>private FragmentTransaction ft;
  private Fragment fragment;
  
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_home_page);
  
      if (findViewById(R.id.fragment_container) != null) {
          if (savedInstanceState != null) {
  
              fragment = getFragmentManager().getFragment(savedInstanceState,"currentFrag");
              ft.replace(R.id.fragment_container, fragment);
              ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
              ft.commit();
          }else{
              fragment = new HomeFragment();
              // In case this activity was started with special instructions from an
              // Intent, pass the Intent's extras to the fragment as arguments
              fragment.setArguments(getIntent().getExtras());
  
              // Add the fragment to the 'fragment_container' FrameLayout
              getFragmentManager().beginTransaction()
                      .add(R.id.fragment_container, fragment).commit();
          }
      }
  </code></pre>
  
  <p>.....</p>
  
  <pre><code>@Override
  protected void onSaveInstanceState(Bundle outState) {
      super.onSaveInstanceState(outState);
      getFragmentManager().putFragment(outState, "currentFrag", fragment);
  }
  </code></pre>
  
  <p>This is the exception in my log cat</p>
  
  <pre><code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.FragmentTransaction android.app.FragmentTransaction.replace(int, android.app.Fragment)' on a null object reference
  </code></pre>
  
  <p>Clearly the current Fragment isn't being saved. Is this generally the correct way to solve this? </p>
  
  <p>This question has nothing to do with the general understanding of what a NullPointerException is but rather how to persist Fragment states when the screen is rotated.</p>