gpt4 book ai didi

java - getApplicationContext() 中的空指针

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:58:19 25 4
gpt4 key购买 nike

我正在尝试以下代码,其中服务正在实现我的监听器:

public class MyListenerClass extends Service implements MyListenerInterface {
public void onCurrencyRecieved(MyEventClass event) {
System.out.println("Coins Recieved - Listener Successful");
stopSelf();
Toast toast = Toast.makeText(getApplicationContext(), "Service Stopped", Toast.LENGTH_LONG);
toast.show();
}

@Override
public void onCreate() {
Toast toast = Toast.makeText(getApplicationContext(),"Service started", Toast.LENGTH_LONG);
toast.show();
super.onCreate();
}

现在,onCreate() 中的 toast 工作正常,但重写方法中的 toast 抛出以下异常:

01-03 18:52:35.740: ERROR/AndroidRuntime(2388): java.lang.NullPointerException
01-03 18:52:35.740: ERROR/AndroidRuntime(2388): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
01-03 18:52:35.740: ERROR/AndroidRuntime(2388): at com.test.listenertest1.MyListenerClass.onCurrencyRecieved(MyListenerClass.java:28)
01-03 18:52:35.740: ERROR/AndroidRuntime(2388): at com.test.listenertest1.MyEventGenerator.generateEvent(MyEventGenerator.java:34)
01-03 18:52:35.740: ERROR/AndroidRuntime(2388): at com.test.listenertest1.MyEventGenerator.<init>(MyEventGenerator.java:16)
01-03 18:52:35.740: ERROR/AndroidRuntime(2388): at com.test.listenertest1.NewActivity.onKeyDown(NewActivity.java:33)
01-03 18:52:35.740: ERROR/AndroidRuntime(2388): at android.view.KeyEvent.dispatch(KeyEvent.java:1037)
01-03 18:52:35.740: ERROR/AndroidRuntime(2388): at android.app.Activity.dispatchKeyEvent(Activity.java:2046)
01-03 18:52:35.740: ERROR/AndroidRuntime(2388): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1631)
01-03 18:52:35.740: ERROR/AndroidRuntime(2388): at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2368)
01-03 18:52:35.740: ERROR/AndroidRuntime(2388): at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2338)
01-03 18:52:35.740: ERROR/AndroidRuntime(2388): at android.view.ViewRoot.handleMessage(ViewRoot.java:1641)
01-03 18:52:35.740: ERROR/AndroidRuntime(2388): at android.os.Handler.dispatchMessage(Handler.java:99)

我想我遗漏了一些重要的 Java 概念。我们不能在覆盖的方法中使用 getApplicationContext() 吗?

最佳答案

您应该尽量避免使用 getApplicationContext(),因为这会大大增加强制关闭的几率。

请改用 YourClass.this,在本例中为 MyListenerClass.this

我想在这个例子中它不起作用,因为 getApplicationContext() after stopSelf()

关于java - getApplicationContext() 中的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8713045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com