This is my code in my first activity:
Intent i = new Intent(this, OtherScreen.class);
i.putExtra("id1", "first");
i.putExtra("id2", "second");
startActivity(i);
where first,second are the values I want to be passed.
and on my other class i have this:
Intent i = getIntent();
Bundle extras = i.getExtras();
String result = extras.getString("id1");
System.out.println("yeah"+result);
but after i run it, my result is null.Can you help me?
If I write my getString in that ways, I am getting syntax errors.
String result = extras.getString(id1); //id1 cannot be resolved to a variable
String result = extras.getString("id1","default value"); // remove argument
Intent i = new Intent(yourcurrentactivity.this, OtherScreen.class);
i.putExtra("id1", "first");
i.putExtra("id2", "second");
startActivity(i);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String result = extras.getString("id1");
System.out.println("yeah"+result);
}
Alternatively for more accuracy, you can use
if(getIntent.hasExtras("id11")'
before actually getting extras from the bundle and do some action if its null
try:
getIntent().getStringExtra("id11");
Of course its best to FIRST check if it even has the extra before you even go for it.
Ref:
http://developer.android.com/reference/android/content/Intent.html#getStringExtra(java.lang.String)
You may try :String result = extras.get("id1");
I was also having trouble with null values. @YuDroid's suggestion to use if (getIntent.hasExtras("id11")
is a good idea. Another safety check that I found when reading the Bundle documentation, though, is
getString(String key, String defaultValue)
That way if the string does not exist you can provide it with a default value rather than it being returned null.
So here is @AprilSmith's answer modified with the default String value.
Intent i = new Intent(yourcurrentactivity.this, OtherScreen.class);
i.putExtra("id1", "first");
i.putExtra("id2", "second");
startActivity(i);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String result = extras.getString("id1", "myDefaultString"); // This line modified
System.out.println("yeah"+result);
}
If anybody still having this issue..here is the solution
the datatype you are passing in first activity should be same in receiving end.
'Intent myIntent = new Intent(D1Activity.this, D2Activity.class);'
'myIntent.putExtra("dval", dval);'
' D1Activity.this.startActivity(myIntent);'
in D2Activity
Bundle extras = getIntent().getExtras();
if (extras != null) {;
edval = extras.getInt ( "dval" );
}
here extras.getString() will not work as we passed an Int not a string