[英]Getting null pointer exception while passing value from Activity to service
在Activity中,我傳遞了一個像這樣的值paramVal
Intent srv = new Intent(this, TestService.class);
startService(srv);
//Intent intent =new Intent("com.example.firstapplication.STARTACTIVITY");
//intent.putExtra("myFirstKey", paramVal);
//intent.putExtra("myFirstKey", paramVal);
Bundle bundle = new Bundle();
bundle.putCharSequence("myFirstKey", paramVal);
intent.putExtras(bundle);
在服務中我正在檢索這樣的值
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Bundle bundle = intent.getExtras();
data = (String) bundle.getCharSequence("myFirstKey");
System.out.println("data checking"+data);
}
但我得到該行的空指針異常
data = (String) bundle.getCharSequence("myFirstKey");
在服務中
我應該在某個地方調用onstart方法嗎? 請讓我知道問題出在哪里?
在您的活動中:
Intent lIntent = new Intent(this, TestService.class);
lIntent.putExtra("myFirstKey", <your String param here>);
startService(lIntent);
在您的服務中:
String lDataString = intent.getStringExtra("myFirstKey");
作為旁注:
你在傳遞額外內容之前就開始了這項服務......
它可能有效,你正在改變指令的順序。 在intent中插入值之前,服務正在啟動。
Intent srv = new Intent(this, TestService.class);
Bundle bundle = new Bundle();
bundle.putCharSequence("myFirstKey", paramVal);
intent.putExtras(bundle);
startService(srv);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.