0

I am getting this error when trying to compile my package.

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.bottomnavigation.BottomNavigationView.setOnNavigationItemSelectedListener(com.google.android.material.bottomnavigation.BottomNavigationView$OnNavigationItemSelectedListener)' on a null object reference
        at com.example.cleverreality.MainActivity.onCreate(MainActivity.java:42)

I believe the issue is the second line of this code but unsure how I would go about fixing it, i've looked lots of stuff online but pretty new to programming.

        BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
        bottomNav.setOnNavigationItemSelectedListener(navListener);
    }
    private BottomNavigationView.OnNavigationItemSelectedListener navListener =
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;

                    switch (item.getItemId()) {
                        case R.id.home:
                            selectedFragment = new HomeFragment();
                            break;
                        case R.id.settings:
                            selectedFragment = new SettingsFragment();
                            break;
                        case R.id.devices:
                            selectedFragment = new DevicesFragment();
                            break;
                    }
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        selectedFragment).commit();

                    return true;
                }
            };
}

Thanks for any help.

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
Sypher
  • 1
  • 2
  • it's null. why is it null ? `findViewById` is failing. why is it failing ? it can't find the view you're trying to reference. for anyone to help with that, you'd need to post more info. either way, it's just a dupe of all other null pointers – a_local_nobody May 31 '21 at 11:37
  • When you say it cant find the view do you mean the bottom navigation one? – Sypher May 31 '21 at 12:20
  • yes, because that's null – a_local_nobody May 31 '21 at 12:21
  • Excuse my ignorance but is it null because I have declared it null, or I have not specified the pointer so its returning as null? – Sypher May 31 '21 at 13:27

0 Answers0