如何使用getApplicationContext()打开Activity?

时间:2018-05-01 13:29:52

标签: android android-context android-bottomnav

我正在使用底部导航菜单,在每个HelpActivity我正在调用一个函数来打开正确的活动:

public void openHomeActivity(){

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

def lines(): bottles = 99 while bottles > 0: yield str(bottles) + ' bottles of pop on the wall!' yield str(bottles) + ' bottles of pop!' yield 'Take one down and pass it around!' bottles -= 1 yield str(bottles) + ' bottles of pop on the wall!' yield '' def sing(): for line in lines(): print(line)

>>> import ninetynine

>>> ninetynine.sing()

99 bottles of pop on the wall!
99 bottles of pop!
Take one down and pass it around!
98 bottles of pop on the wall!

98 bottles of pop on the wall!
98 bottles of pop!
Take one down and pass it around!
97 bottles of pop on the wall!

...

1 bottles of pop on the wall!
1 bottles of pop!
Take one down and pass it around!
0 bottles of pop on the wall!

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

错误

  

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

1 个答案:

答案 0 :(得分:2)

HelpActivity help = new HelpActivity();

从不自行创建活动实例。

openHomeActivity()修改为:

public void openHomeActivity(Context context){

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

然后,当您调用它时,请传入现有的Context ,例如具有底部导航视图的Activity