Passing values through bundle and get its value on

2019-01-25 07:50发布

I am passing value through Bundle as you can see in my code.
Now, I want its value in another activity onCreate(). I tried it to get its value but it is showing nullpointerexception.

Please help me solve the problem.

Bundle bundle = new Bundle();
String url = "http://www.google.com";
bundle.putString("url", url);
Intent myIntent = new Intent(context, NotificationService.class);
myIntent.putExtras(bundle);
context.startService(myIntent);


Get Value code :

if (!getIntent().getExtras().getString("url").contains(null)) {
        // Do something
}

10条回答
做个烂人
2楼-- · 2019-01-25 08:00

//put value in intent like this

    Intent in = new Intent(MainActivity.this, Booked.class);
    in.putExtra("filter", "Booked");
    startActivity(in);

// get value from bundle like this

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    String filter = bundle.getString("filter");
查看更多
神经病院院长
3楼-- · 2019-01-25 08:00

Replace startService(...) - > startActivity(...)

And Also replace

if (getIntent().getExtras().getString("url").contains(null)) {
        // retrieve the url
}

TO

if (getIntent().getExtras().getString("url") != null) {
        // retrieve the url
}
查看更多
走好不送
4楼-- · 2019-01-25 08:00
  1. Intent serviceIntent = new Intent(YourService.class.getName()); serviceIntent.putExtra("url", "www.google.com"); context.startService(serviceIntent);

    1. When the service is started its onStartCommand() method will be called so in this method you can fetch the value (url) from the intent object

    2. public int onStartCommand (Intent intent, int flags, int startId){

    String userID = intent.getStringExtra("url");

    return START_STICKY; }

查看更多
Fickle 薄情
5楼-- · 2019-01-25 08:01

Because you put your strings inside a bundle

Bundle youtbundle = new Bundle();
String url = "http://www.google.com";
yourbundle.putString("url", url);

And then put the bundle as an extra to the intent

Intent myIntent = new Intent(context, NotificationService.class);
myIntent.putExtras(yourbundle);
context.startService(myIntent);

In the begining You have to strip the bundle from extras

Bundle yourbundle = getIntent().getExtras().getBundle("yourbundle") ;

Then get Strings from yourbundle

if (!yourbundle.getString("url").contains(null)) {
     // Do something
}
查看更多
孤傲高冷的网名
6楼-- · 2019-01-25 08:01

String value = bundle.getString("request");

查看更多
唯我独甜
7楼-- · 2019-01-25 08:04

try this

 String url = "http://www.google.com";

Intent myIntent = new Intent(context, NotificationService.class);
myIntent.putExtras("url", url);
startActivity(myIntent);

and on another activity get it like

Bundle extra = getIntent().getExtras();
if(extra != null) {
String value = extra.getString("url")
//use this value where ever you want

  }
查看更多
登录 后发表回答