Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing values through bundle and get its value on another activity

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
}
like image 726
Jeeten Parmar Avatar asked Jun 10 '13 10:06

Jeeten Parmar


People also ask

What is used to pass data from one activity to another activity?

We can send the data using the putExtra() method from one activity and get the data from the second activity using the getStringExtra() method.

Which intent method will let you retrieve the data from another activity?

You use getIntent() to get the Intent that started the second activity. Then you can extract the data with getExtras() and the key you defined in the first activity.


3 Answers

This should be the procedure.

Create a new Intent with bundle and start the activity.

Intent i = new Intent(context, ActivityName.class);
i.putExtra("key", mystring);
startActivity(i);

Take the bundle like this in new Activity inside onCreate

Bundle extras = getIntent().getExtras();
String value;
if (extras != null) {
  value = extras.getString("key");
}
like image 120
Sreedev Avatar answered Oct 16 '22 14:10

Sreedev


Hi i hope this code helps you.

Bundle bundle = new Bundle();
bundle.putString("name", "Android");
bundle.putString("iname", "iPhone");
Intent intent = new Intent(getApplicationContext(), MyActivity.class);
intent.putExtras(bundle);
startActivity(intent);

In MyActivity.class

public Bundle getBundle = null;
getBundle = this.getIntent().getExtras();
String name = getBundle.getString("name");
String id = getBundle.getString("iname");
like image 41
Bebin T.N Avatar answered Oct 16 '22 14:10

Bebin T.N


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

you have to check against null values

like image 28
Blackbelt Avatar answered Oct 16 '22 12:10

Blackbelt