2011-08-23 44 views
20

我有一个我试图启动的IntentService。当我这样做,它吐出这个:空指针异常开始IntentService

java.lang.RuntimeException: Unable to start service [email protected] with Intent { cmp=com.pec.testapp/.service.NewsService }: java.lang.NullPointerException 
    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2173) 
    ... (omitted for brevity) 
Caused by: java.lang.NullPointerException 
    at android.app.IntentService.onStart(IntentService.java:110) 
    at android.app.IntentService.onStartCommand(IntentService.java:118) 
    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2160) 
    ... 10 more 

我GOOGLE了这一点,看着尽可能多的类似StackOverflow问题,我可以找到。但是,我无法将头部包裹起来,有一些微妙的差异。首先,在例外中没有任何我的类引用。其次,类似的问题已经通过改变上下文或双重检查来确定它不是空的。

我的代码检查情况并非如此:

public Context context; 
@Override 
public void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    context = getApplicationContext(); 

    if(context == null) 
     Log.d("PECAPP","Context is null"); 

    setContentView(R.layout.news_layout); 

    ...Omit button code... 
    button.setOnClickListener(new OnClickListener(){ 
     @Override 
     public void onClick(View view){ 
      Intent i = new Intent(context, NewsService.class); // also tried NewsActivity.this 
      if(i != null) // I know that this should never happen but I'm at a loss... 
       startService(i); // I've also tried this with context.startService(i) 
     } 
    }); 

} 

我IntentService是谷歌文档蓝本。只需一个带有onHandleIntent方法的构造函数。

public NewsService() { 
    super("NewsService"); 
} 

...omit onCreate() and onDestroy() since they haven't been implemented yet... 

@Override 
protected void onHandleIntent(Intent intent) throws IllegalArgumentException { 
    Log.d("PECAPP","Got here..."); // I never actually got here... 
    if(intent == null) Log.d("PECAPP","INTENT IS NULL"); 
    ...omit rest of code... 
} 

所以我的问题是这样的:这哪里是例外,来自哪里,是有什么我可以做的不同,以避免呢?我的google-fu在过去并没有让我失望,所以希望这不是那些痛苦明显的答案之一。此外,如果有事情可以做得更好或者只是简单的丑陋,建设性的批评总是值得赞赏的。

我把全部例外,NewsActivity和NewsService放在pastebin中,以防我遗漏了某些东西。 http://pastebin.com/mR9Sykrq

回答

50

如果您打算在IntentService中覆盖onCreate(),请确保您在其中调用super.onCreate()。这似乎很可能是你的问题。

+3

通常,如果您在活动中忘记了这一点,它会在您崩溃时提醒您,但显然不在此处。 –

+0

@Jarett只是Android =] –

+0

许多奇观的一个例子谢谢,它适用于我。 – mxi1

8

不知道它是同样的问题,但我使用intentService也和我有使用

context = getApplicationContext(); 

或 上下文= getBaseContext()麻烦; 我没有覆盖的onCreate所以以前的解决方案可能是你的解决方案, 我工作里面的“onHandleIntent”

我会得到一个即时异常与第一和异常后,当我试图使用第二。

我最终意识到Intentservice本身就是Context的一个子类,所以我在需要“Context”实例的地方替换“this”。

这解决了我的问题。

+0

这可以帮助我很多。 –

+0

与您的问题面临同样的问题。非常感谢..你为我节省了很多时间 – Yasir

+0

我得到了appContext'Context appContext = getApplicationContext()'的空值。 – kAmol