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

时间:2018-04-18 17:44:28

标签: java android

I created a navigation drawer with fragments but I get the error mentioned in the title. When I run the app and click on a menu item, instead of initializing the fragment, it just crashes. Any help would be greatly appreciated.

ActivityMain:

public class MainActivity extends AppCompatActivity {

private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
    mDrawerLayout.addDrawerListener(mToggle);
    NavigationView nvDrawer = (NavigationView) findViewById(R.id.nv);
    mToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    setupDrawerContent(nvDrawer);
}

@Override
    public boolean onOptionsItemSelected (MenuItem item) {
        if (mToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

public void selectItemDrawer (MenuItem menuItem){
    android.support.v4.app.Fragment myFragment = null;
    Class fragmentClass;
    switch (menuItem.getItemId()){
        case R.id.home:
            fragmentClass= home.class;
            break;
        case R.id.planning:
            fragmentClass= planning.class;
            break;
        case R.id.meal:
            fragmentClass= foodOmatic.class;
            break;
        case R.id.recipes:
            fragmentClass= recipes.class;
            break;
        case R.id.extra:
            fragmentClass= extra.class;
            break;
        case R.id.options:
            fragmentClass= options.class;
            break;
        case R.id.logout:
            fragmentClass= logoff.class;
            break;

        default:
            fragmentClass = home.class;

    }
    try {
        myFragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.flcontent,myFragment).commit();
    menuItem.setChecked(true);
    setTitle(menuItem.getTitle());
    mDrawerLayout.closeDrawers();
}

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            selectItemDrawer(item);
            return true;
        }
    });
}

And here is the logcat:

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:392)
    at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:439)
    at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:430)
    at com.example.android.meat_timealpha10.Activities.MainActivity.selectItemDrawer(MainActivity.java:88)
    at com.example.android.meat_timealpha10.Activities.MainActivity$1.onNavigationItemSelected(MainActivity.java:98)
    at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:156)
    at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
    at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
    at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
    at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:342)
    at android.view.View.performClick(View.java:6294)
    at android.view.View$PerformClick.run(View.java:24770)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

I understand it probably has something to do with android.support.v4.app.Fragment myFragment = null; But I don't know how else to do this. Thanks in advance for your help!

2 个答案:

答案 0 :(得分:1)

This is because you call newInstance() on your fragmentClass, and the fragmentClass object is null at the time of your call. You should create the actual Class object you want by something similar to

case R.id.home:
    fragmentClass = new HomeFragment(); //for home
    break;

And so on for each different possible class so when you call newInstance(), your fragmentClass is not null.

答案 1 :(得分:0)

Your problem is in the default:return default:fragmentClass = home.class; according to the Java documentation

The default section handles all values that are not explicitly handled by one of the case sections.

Please take a look at my answer here