1

I don't have this code in MainActivity.java, I have it in one called Login.java

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);
}
snow915
  • 13
  • 1
  • 3

1 Answers1

0

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);
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
  • 1
    Now i have this: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.material.navigation.NavigationView.getHeaderView(int)' on a null object reference – snow915 Feb 29 '20 at 18:19
  • you should use `findViewById(R.id.your_id)` . Check your id `nav_view` exists in xml? – IntelliJ Amiya Feb 29 '20 at 18:21
  • Yes, it exists in activity_main.xml – snow915 Feb 29 '20 at 18:23
  • 1
    I don't have this code in MainActivity.java, I have it in one called Login.java – snow915 Feb 29 '20 at 18:26
  • @snow915 Your `NavigationView` belongs from which Activity? – IntelliJ Amiya Feb 29 '20 at 18:28
  • It's in Login.java – snow915 Feb 29 '20 at 18:31
  • `Yes, it exists in activity_main.xml ` & `I don't have this code in MainActivity.java`. Seems like your NavigationView coming from MainActivity. If your NavigationView coming from from MainActivity(layout will activity_main) then write your code MainActivity section else Login Activity section. – IntelliJ Amiya Feb 29 '20 at 18:42