I have this error in the Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Menu com.google.android.material.navigation.NavigationView.getMenu()' on a null object reference at com.store.Credenciales.Login.addMenuItemLogOut(Login.java:93)
My code in Login.java:93 is this function:
private void addMenuItemLogOut(){
NavigationView navigationView= (NavigationView) findViewById(nav_view);
Menu menu = navigationView.getMenu(); //Line 93
menu.findItem(R.id.nav_signin).setVisible(false);
menu.findItem(R.id.nav_send).setVisible(true);
}
And command to bring the function higher, when a user entered correct username and password
if(isLogin){
addMenuItemLogOut(); //Here
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("user_id", userd);
intent.putExtras(bundle);
startActivity(intent);
}
NullPointerException
is thrown when an application attempts to use an object reference that has the null value.
You should use getHeaderView (int index) instead of getMenu() .
Gets the header view at the specified position.
Try with
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
navigationView.getMenu().findItem(R.id.nav_signin).setVisible(false);
navigationView.getMenu().findItem(R.id.nav_send).setVisible(true);