2011-08-23 85 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