0

I'm using a bottom navigation menu, on each itemMenu i'm calling a function to open the correct Activity:

//In the  activty "A" where there's the bottom nav bar:

HelpActivity help = new HelpActivity();

                case R.id.navigation_home:
                help.openHomeActivity();

In the HelpActivity

public void openHomeActivity(){

    Intent i = new Intent(getApplicationContext(), HomeActivity.class);
    startActivity(i);
}

The app crashes, how to solve this, please?

the error

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Machine
  • 3
  • 4
  • 1
    App crashes then what is error inside logcat ??? Post it here. And also check inside manifest you declared *HomeActivity* or not. – Jay Rathod May 01 '18 at 13:31

1 Answers1

2
HelpActivity help = new HelpActivity();

Never create an instance of an activity yourself.

Modify openHomeActivity() to be:

public void openHomeActivity(Context context){

    Intent i = new Intent(context, HomeActivity.class);
    startActivity(i);
}

Then, when you call it, pass in an already existing Context, such as the Activity that has your bottom navigation view.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • But how to call the openHomeActivity()? – Machine May 01 '18 at 13:42
  • @Machine: Put `openHomeActivity()` on the class where the `switch` block with the `case R.id.navigation_home` stuff is. Or, get rid of the method and just call `startActivity()` from inside the `case R.id.navigation_home` block. – CommonsWare May 01 '18 at 13:46
  • I did not know we could call the startActivity() away from the intent, now i can use a classHelp, Thank you so much for your help and time – Machine May 01 '18 at 13:48
  • `openHomeActivity(this);` – 92AlanC May 01 '18 at 13:54