简体   繁体   中英

Getting null pointer exception while passing value from Activity to service

In Activity i have passed a value paramVal like this

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

and in service I am retrieving a value like this

 @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);
     }

but i am getting null pointer exception for the line

data = (String) bundle.getCharSequence("myFirstKey");

in service

should i have to call onstart method in service somewhere. Please let me know where is the problem??

In your Activity:

Intent lIntent = new Intent(this, TestService.class);
lIntent.putExtra("myFirstKey", <your String param here>);
startService(lIntent);

In your Service:

String lDataString = intent.getStringExtra("myFirstKey");

As a sidenote:

  • please override onStartCommand() in your service, since onStart() is deprecated
  • it is not required to call super.onStartCommand() (or super.onStart() for that matter) when extending the Service class

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

It might work, you are changing the order of instruction. the service is starting before inserting values in the intent.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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