【问题标题】:Getting null pointer exception while passing value from Activity to service将值从 Activity 传递给服务时出现空指针异常
【发布时间】:2012-08-16 08:03:58
【问题描述】:

在 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 方法。请告诉我问题出在哪里??

【问题讨论】:

  • 见android-coding.blogspot.in/2011/03/… tuts 用于将数据从 Activity 传递到 Serivce 以及在您当前的代码中,您在将价值放入意图之前启动服务,因此在准备好意图后启动它

标签: android service android-intent


【解决方案1】:

在您的活动中:

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())

【讨论】:

    【解决方案2】:

    您在传递附加功能之前启动服务...

    【讨论】:

    • 好的,我应该这样写 Intent srv = new Intent(this, TestService.class);捆绑捆绑 = 新捆绑(); bundle.putCharSequence("myFirstKey", paramVal);意图.putExtras(捆绑);启动服务(srv);
    【解决方案3】:

    它可能会起作用,你正在改变指令的顺序。服务在 Intent 中插入值之前启动。

    Intent srv = new Intent(this, TestService.class);
    Bundle bundle = new Bundle();
        bundle.putCharSequence("myFirstKey", paramVal);
        intent.putExtras(bundle);
    startService(srv);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      • 2011-03-15
      相关资源
      最近更新 更多