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.<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(),因为这会大大增加获得Force Closes的机会.

而是使用YourClass.this,在本例中为MyListenerClass.this.

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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...