如何使用getApplicationContext()打开活动? [英] How to Open Activity using getApplicationContext()?

查看:111
本文介绍了如何使用getApplicationContext()打开活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用底部导航菜单,在每个 itemMenu 上,我都在调用一个函数来打开正确的Activity:

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();

HelpActivity

public void openHomeActivity(){

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

该应用程序崩溃了,请问该如何解决?

The app crashes, how to solve this, please?

错误

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.content.Context android.content.Context.getApplicationContext()'

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

推荐答案

HelpActivity help = new HelpActivity();

从不自己创建活动的实例.

Never create an instance of an activity yourself.

openHomeActivity()修改为:

public void openHomeActivity(Context context){

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

然后,当您调用它时,传递已经存在的 Context ,例如具有底部导航视图的 Activity .

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

这篇关于如何使用getApplicationContext()打开活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆