英文:
Android App keeps on crashing upon new Intent
问题
我有这个错误代码:Caused by: java.lang.NullPointerException: 尝试在空对象引用上调用虚拟方法'java.lang.String android.content.Context.getPackageName()'
这一行:Intent callMode = new Intent(MainActivity.this, IncallActivity.class);
我正在尝试的是在接到电话时设置一个新的活动。以下功能是应该“切换”到该活动的功能。
public void callMode() {
Intent callMode = new Intent(MainActivity.this, IncallActivity.class);
startActivity(callMode);
}
它位于MainActivity类的外部,不在onCreate函数中。
当我尝试将其放在onCreate函数中(当然没有public void callMode()
)时,它可以工作,但这不是目标。
我正在尝试从另一个监听电话的类中激活这个新的活动。
public class CallReceiver extends BroadcastReceiver {
IncallActivity incallActivity = new IncallActivity();
public MainActivity mainActivity;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
mainActivity.callMode();
} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)) {
incallActivity.endCallMode();
}
}
}
所以为什么会出现这个错误呢?
英文:
So I've got this error code: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
The line: Intent callMode = new Intent(MainActivity.this, IncallActivity.class);
What I'm trying to do is to set a new activity when I receive a call. The following function is what should "switch" to that activity.
public void callMode() {
Intent callMode = new Intent(MainActivity.this, IncallActivity.class);
startActivity(callMode);
}
And it is located inside of the MainActivity class, outside of the onCreate function.
When I try to put it inside of the onCreate function (without public void callMode()
of course) it works, but that's not the goal.
I'm trying to activate this new activity from another class, which listens for calls.
public class CallReceiver extends BroadcastReceiver {
IncallActivity incallActivity = new IncallActivity();
public MainActivity mainActivity;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
mainActivity.callMode();
} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)) {
incallActivity.endCallMode();
}
}
}
So why does this error show up?
答案1
得分: 0
我找到了一种方法来做到这一点。
您需要在代码中添加一个 public static Context context
,然后在 onCreate
中执行 context = getBaseContext();
从那里,您可以从任何类中启动第二个活动。
英文:
I found a way to do it.
You need to add a public static Context context
to your code, and then in onCreate, do context = getBaseContext();
From there you can launch the second activity from any class you'd like.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论