[英]Null Pointer exception starting IntentService
我有一個我正在嘗試啟動的IntentService。 當我這樣做時,它會吐出這個:
java.lang.RuntimeException: Unable to start service com.pec.testapp.service.NewsService@406bd940 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
我已經搜索了這個,並查看了盡可能多的類似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是在google docs之后建模的。 只是一個帶有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
如果您要在IntentService
覆蓋onCreate()
,請確保在其中調用super.onCreate()
。 這似乎很可能是你的問題。
不確定它是否是同一個問題,但我也使用了intentService,而我在使用時遇到了麻煩
context = getApplicationContext();
或context = getBaseContext(); 我沒有壓倒於創建所以以前的解決方案可能是你的解決方案,我在“onHandleIntent”里面工作
我會在第一個時獲得一個立即異常,而在我嘗試使用第二個時會出現異常。
我最終意識到Intentservice本身就是Context的子類,所以我在需要“Context”實例的地方替換了“this”。
這解決了我的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.