java getapplicationcontext_java – getApplicationContext()中的空指针
我正在嘗試以下代碼,其中一個服務正在實現我的監聽器:
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工作正常,但是在重寫方法內部拋出以下異常:
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.(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()嗎?
總結
以上是生活随笔為你收集整理的java getapplicationcontext_java – getApplicationContext()中的空指针的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: matlab2018a安装激活教程
- 下一篇: 轻量社交APP系统ThinkSNS 简
