Nullpointerexception during Fragment replacement

I've made some fragment change from one to another. But when I use this function, application is stopped. What should I do? Here is my code and Logcat .

Here is the Logcat.

07-11 12:45:09.787 8825-8825/? I/art: Not late-enabling -Xcheck:jni (already on)
07-11 12:45:09.855 8825-8825/com.example.yangseungchan.navigationdrawer W/System: ClassLoader referenced unknown path: /data/app/com.example.yangseungchan.navigationdrawer-2/lib/x86_64
07-11 12:45:09.875 8825-8825/com.example.yangseungchan.navigationdrawer W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-11 12:45:10.089 8825-8825/com.example.yangseungchan.navigationdrawer I/art: Rejecting re-init on previously-failed class java.lang.Class<android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper>
    Rejecting re-init on previously-failed class java.lang.Class<android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper>
07-11 12:45:10.185 8825-8841/com.example.yangseungchan.navigationdrawer D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
07-11 12:45:10.226 8825-8841/com.example.yangseungchan.navigationdrawer I/OpenGLRenderer: Initialized EGL, version 1.4
07-11 12:45:10.227 8825-8841/com.example.yangseungchan.navigationdrawer W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
07-11 12:45:10.235 8825-8841/com.example.yangseungchan.navigationdrawer D/EGL_emulation: eglCreateContext: 0x7f18e1034b40: maj 3 min 0 rcv 3
07-11 12:45:10.241 8825-8841/com.example.yangseungchan.navigationdrawer D/EGL_emulation: eglMakeCurrent: 0x7f18e1034b40: ver 3 0 (tinfo 0x7f18e1002660)
07-11 12:45:10.242 8825-8841/com.example.yangseungchan.navigationdrawer E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
    glUtilsParamSize: unknow param 0x00008824
07-11 12:45:10.291 8825-8841/com.example.yangseungchan.navigationdrawer D/EGL_emulation: eglMakeCurrent: 0x7f18e1034b40: ver 3 0 (tinfo 0x7f18e1002660)
07-11 12:45:30.497 8825-8825/com.example.yangseungchan.navigationdrawer D/AndroidRuntime: Shutting down VM
07-11 12:45:30.497 8825-8825/com.example.yangseungchan.navigationdrawer E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.yangseungchan.navigationdrawer, PID: 8825
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
        at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:396)
        at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:444)
        at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:434)
        at com.example.yangseungchan.navigationdrawer.MainActivity.onFragmentChanged(MainActivity.java:82)
        at com.example.yangseungchan.navigationdrawer.InformationFragment$1.onClick(InformationFragment.java:28)
        at android.view.View.performClick(View.java:5198)
        at android.view.View$PerformClick.run(View.java:21147)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-11 12:45:31.824 8825-8825/? I/Process: Sending signal. PID: 8825 SIG: 9

**[MainActivity.java:82], [InformationFragment.java:28] is blue line.

And Here is the MainActivity.java

1. package com.example.yangseungchan.navigationdrawer;
2.
3. import android.support.annotation.NonNull;
4. import android.support.design.widget.NavigationView;
5. import android.support.v4.view.GravityCompat;
6. import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
    private DrawerLayout drawer;
    InformationFragment informationFragment;
    InformationFragment2 informationFragment2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        informationFragment = (InformationFragment)getSupportFragmentManager().findFragmentById(R.id.informationFragment);
        informationFragment2 = new InformationFragment2();

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        if(savedInstanceState == null){
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new InformationFragment()).commit();
            navigationView.setCheckedItem(R.id.nav_information);
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        switch(menuItem.getItemId()){
            case R.id.nav_information:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new InformationFragment()).commit();
                break;
            case R.id.nav_map:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MapFragment()).commit();
                break;
            case R.id.nav_help:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HelpFragment()).commit();
                break;
            case R.id.nav_sending:
                Toast.makeText(this, "Sending has been done successfully",Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_download:
                Toast.makeText(this, "Downloading has been done successfully",Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_setting:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new SettingFragment()).commit();
                break;

        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed(){
        if(drawer.isDrawerOpen(GravityCompat.START)){
            drawer.closeDrawer(GravityCompat.START);
        }
        else{
            super.onBackPressed();
        }
    }

    public void onFragmentChanged(int index){
        if(index == 0){
            82. getSupportFragmentManager().beginTransaction().replace(R.id.container,informationFragment).commit();
        }
        else{
            getSupportFragmentManager().beginTransaction().replace(R.id.container, informationFragment2).commit();
        }
    }
}

MainActivity 82 is

public void onFragmentChanged(int index){
        if(index == 0){
            82. getSupportFragmentManager().beginTransaction().replace(R.id.container,informationFragment).commit();
        }
        else{
            getSupportFragmentManager().beginTransaction().replace(R.id.container, informationFragment2).commit();
        }
    }
}

And the InformationFragment.java is here

  package com.example.yangseungchan.navigationdrawer;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;



public class InformationFragment extends Fragment {
    private DrawerLayout drawer;
    @Nullable
    @Override


    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_information,container,false);
        Button nextButton = (Button)rootView.findViewById(R.id.nextButton);
        nextButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                MainActivity activity = (MainActivity)getActivity();
                activity.onFragmentChanged(0);
            }

        });

        return rootView;
    }


}

And the Information.java : 28 is

 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_information,container,false);
        Button nextButton = (Button)rootView.findViewById(R.id.nextButton);
        nextButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                MainActivity activity = (MainActivity)getActivity();
                28. activity.onFragmentChanged(0);
            }

        });

        return rootView;
    }

2 answers

  • answered 2018-07-11 04:30 VicJordan

    You are not getting activity reference here i.e. it is null due to which your app is crashing. Move your this code to onAttach() method.

    Your code will be like below:

      @Override
      public void onAttach(Activity activity) {
          super.onAttach(activity);
          mNextButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                MainActivity activity = (MainActivity)getActivity();
                activity.onFragmentChanged(0);
            }
        });
      }
    

    Note: make mNextButton class variable i.e. declare outside onCreateView.

  • answered 2018-07-11 04:32 Anmol

    I think you are not able to initialise the object of the fragment that you are trying to replace.

    //instead of initialising it this way 
    informationFragment = (InformationFragment)getSupportFragmentManager().findFragmentById(R.id.informationFragment);
    
    //try using 
    informationFragment = new InformationFragment();