我有一個我試圖啓動的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
通常,如果您在活動中忘記了這一點,它會在您崩潰時提醒您,但顯然不在此處。 –
@Jarett只是Android =] –
許多奇觀的一個例子謝謝,它適用於我。 – mxi1