繁体   English   中英

在将值从Activity传递给服务时获取空指针异常

[英]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");

作为旁注:

  • 请覆盖您服务中的onStartCommand(),因为不推荐使用onStart()
  • 扩展Service类时不需要调用super.onStartCommand()(或者super.onStart())

你在传递额外内容之前就开始了这项服务......

它可能有效,你正在改变指令的顺序。 在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM