片段替换期间的NullpointerException

时间:2018-07-11 04:19:42

标签: java android nullpointerexception fragmentmanager

我已经将一些片段更改为另一个片段。但是当我使用此功能时,应用程序停止了。我该怎么办?这是我的代码和Logcat。

这是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]是蓝线。

这是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是

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();
        }
    }
}

InformationFragment.java在这里

  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;
    }


}

Information.java:28是

 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 个答案:

答案 0 :(得分:0)

您在这里没有获得activity参考,即您的应用崩溃是null。 将此代码移至onAttach()方法。

您的代码如下:

  @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);
        }
    });
  }

注意:设置mNextButton类变量,即在onCreateView外部声明。

答案 1 :(得分:0)

我认为您无法初始化要替换的片段的对象。

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

//try using 
informationFragment = new InformationFragment();