title: Android OnBackpressed in Fragment Null Exception
body: <p>Hello I'm trying to override back button to back to home page it gives me this error when press back from BasicInfoFragment  then press back again in home fragment (MainFragment)
  it gives </p>
  
  <p>java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentManager android.support.v4.app.FragmentActivity.getSupportFragmentManager()' on a null object reference</p>
  
  <p><strong>then the application crushs</strong> </p>
  
  <blockquote>
    <p>java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentManager android.support.v4.app.FragmentActivity.getSupportFragmentManager()' on a null object reference
                                                                                   at com.teqneia.blooddonation.BasicInfoFragment.doBack(BasicInfoFragment.java:245)
                                                                                   at com.teqneia.blooddonation.MainActivity.onBackPressed(MainActivity.java:258)
                                                                                   at android.app.Activity.onKeyUp(Activity.java:2530)
                                                                                   at android.view.KeyEvent.dispatch(KeyEvent.java:2726)
                                                                                   at android.app.Activity.dispatchKeyEvent(Activity.java:2798)
                                                                                   at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:543)
                                                                                   at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:53)
                                                                                   at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:315)
                                                                                   at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:53)
                                                                                   at com.android.internal.policy.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:2368)
                                                                                   at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4333)
                                                                                   at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4295)
                                                                                   at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3836)
                                                                                   at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3889)
                                                                                   at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3855)
                                                                                   at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3981)
                                                                                   at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3863)
                                                                                   at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4038)
                                                                                   at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3836)
                                                                                   at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3889)
                                                                                   at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3855)
                                                                                   at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3863)
                                                                                   at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3836)
                                                                                   at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3889)
                                                                                   at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3855)
                                                                                   at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4014)
                                                                                   at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:4175)
                                                                                   at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2378)
                                                                                   at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1999)
                                                                                   at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1990)
                                                                                   at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:2355)
                                                                                   at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
                                                                                   at android.os.MessageQueue.nativePollOnce(Native Method)
                                                                                   at android.os.MessageQueue.next(MessageQueue.java:330)
                                                                                   at android.os.Looper.loop(Looper.java:137)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5546)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)</p>
  </blockquote>
  
  <p>BasicInfoFragment java</p>
  
  <pre><code>public class BasicInfoFragment extends Fragment implements MainActivity.OnBackPressedListener, View.OnClickListener {
  .
  .
  
  public BasicInfoFragment() {
  }
  
  
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.fragment_basic_info, container, false);
  
      initialize(view);
  
      // Inflate the layout for this fragment
      return view;
  }
  
  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
      super.onViewCreated(view, savedInstanceState);
      ((MainActivity) getActivity()).setOnBackPressedListener(this);
  }
  
  void initialize(View view) {
      //VIEW OLD DATA AND ADD LISTENERS
      name = (EditText) view.findViewById(R.id.name_edit);
  
      email = (EditText) view.findViewById(R.id.email_edit);
      mobile = (EditText) view.findViewById(R.id.mobile_edit);
      LastDonation = (EditText) view.findViewById(R.id.date_edit);
      LastDonation.setInputType(InputType.TYPE_NULL);
      LastDonation.requestFocus();
      LastDonation.setOnClickListener(this);
  
      //TAKE DATA FROM SERVER
      //name.setText("");
      //email.setText();
      //mob.setText();
      //LastDonation.setText();
  
      b = (Button) view.findViewById(R.id.save_edit);
      b.setOnClickListener(this);
      //get Radio Groups
  
      radioBgGroup = (RadioGroup) view.findViewById(R.id.bg_edit);
      radioRhGroup = (RadioGroup) view.findViewById(R.id.rh_edit);
  
      if (mSharedGetter.getBloodType().equals("A")) {
  
  }
  
  
  
  
  
  @Override
  public void doBack() {
      Fragment fragment = null;
      fragment = new MainFragment();
      FragmentManager fm = getActivity().getSupportFragmentManager();
      FragmentTransaction transaction = fm.beginTransaction();
      transaction.replace(R.id.fragment_container, fragment);
      transaction.commit();
  }
  </code></pre>
  
  <blockquote>
    <p>MainActivity</p>
  </blockquote>
  
  <pre><code>public class MainActivity extends AppCompatActivity
          implements NavigationView.OnNavigationItemSelectedListener {
  
      .
              .
              .
              .
              .
              .
      protected OnBackPressedListener onBackPressedListener;
  
  
      public interface OnBackPressedListener {
          void doBack();
      }
  
      public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
          this.onBackPressedListener = onBackPressedListener;
      }
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
  
  
          //Initially Load MainFFragment xml
          setContentView(R.layout.activity_main);
          Fragment fragment = new MainFragment();
          //Apply fragment
          FragmentTransaction fragmentTransaction =
                  getSupportFragmentManager().beginTransaction();
          fragmentTransaction.replace(R.id.fragment_container, fragment);
          fragmentTransaction.commit();
  
  
          Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
          setSupportActionBar(toolbar);
  
  
          DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
  
          ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                  this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
          drawer.setDrawerListener(toggle);
          toggle.syncState();
  
          NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
          View header = navigationView.getHeaderView(0);
          TVnav_name = (TextView) header.findViewById(R.id.nav_name);
          navigationView.setNavigationItemSelectedListener(this);
          TVnav_name.setText(mSharedGetter.getUserName());
      }
  
  
      @Override
      public void onBackPressed() {
          DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
          if (drawer.isDrawerOpen(GravityCompat.START)) {
              drawer.closeDrawer(GravityCompat.START);
          } else if (onBackPressedListener != null)
              onBackPressedListener.doBack();
          else
              super.onBackPressed();
      }
  
      @Override
      protected void onDestroy() {
          onBackPressedListener = null;
          super.onDestroy();
      }
  
      @SuppressWarnings("StatementWithEmptyBody")
      @Override
      public boolean onNavigationItemSelected(MenuItem item) {
          // Handle navigation view item clicks here.
          int id = item.getItemId();
          Fragment fragment = null;
  
  
          if (id == R.id.nav_edit_info) {
  
              fragment = new BasicInfoFragment();
              if (fragment != null) {
                  //Apply fragment
                  FragmentTransaction fragmentTransaction =
                          getSupportFragmentManager().beginTransaction();
                  fragmentTransaction.replace(R.id.fragment_container, fragment);
                  fragmentTransaction.commit();
              }
  
  
          } else if (id == R.id.nav_home) {
              fragment = new MainFragment();
  
              if (fragment != null) {
                  //Apply fragment
                  FragmentTransaction fragmentTransaction =
                          getSupportFragmentManager().beginTransaction();
                  fragmentTransaction.replace(R.id.fragment_container, fragment, "MY_FRAGMENT");
                  fragmentTransaction.commit();
              }
          }
  
  
          DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
          drawer.closeDrawer(GravityCompat.START);
          return true;
      }
  
  
  }
  </code></pre>
  
  <blockquote>
    <p>MainFragment</p>
  </blockquote>
  
  <pre><code>public class MainFragment extends Fragment{
  
  
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                               Bundle savedInstanceState) {
  
          // Inflate the layout for this fragment
          View view = inflater.inflate(R.layout.fragment_main, container, false);
  
  
  
  
  
          return view;
      }
  
  
  
  
  
          //DIALOG BUILDER
          new AlertDialog.Builder(getActivity())
                  .setTitle("DONATION REQUEST")
                  .setView(dialogView)
                  .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int which) {
                      }
                  })
                  .setPositiveButton("Request now", new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int which) {
                          //Send the request
  
                          Dialog f = (Dialog) dialog;
  
                      }
                  }).show();
  
  
      }
  
  
  }
  </code></pre>