In addition to the fragments, I want to add a transition to my navigation drawer as well.

public boolean onNavigationItemSelected(MenuItem item) { int id = item.getItemId(); Fragment fragment = null; if (id == R.id.nav_camera) { fragment = new MainFragment(); } else if (id == R.id.nav_gallery) { fragment = new SecondFragment(); } else if (id == R.id.nav_slideshow) { startActivity(new Intent(getApplicationContext(), MainActivity.class)); } android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.commit(); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } 

If there are no problems when navigating through fragments, then when you go to MainActivity, you get an error

  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference 

    1 answer 1

    The fact is that the code in your method continues to run after the call to startActivity() . In the method, you assign fragment value to null, then you do not initialize it (the corresponding condition branches are skipped) and then (after calling the second activation) you try to call a fragment that is null, and you get an error about it.

    You can do, for example, like this:

     public boolean onNavigationItemSelected(MenuItem item) { android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); switch (item.getItemId()) { case R.id.nav_camera : fragmentTransaction.replace(R.id.fragment_container, new MainFragment()).commit(); break; case R.id.nav_gallery : fragmentTransaction.replace(R.id.fragment_container, new SecondFragment()).commit(); break; case R.id.nav_slideshow : startActivity(new Intent(this, MainActivity.class)); break; } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } 
    • Thank. "Shorter", in a nutshell, you can get a tip? Perhaps it will apply. Plus, it is interesting to find out why this solution is not entirely successful. - Morozov
    • one
      @VadimMorozov The first thing that came to mind from the "more beautiful" :) - pavlofff