Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

android - How to Open Activity using getApplicationContext()?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...