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
If anybody still having this issue..here is the solution
the datatype you are passing in first activity should be same in receiving end.
in D2Activity
here extras.getString() will not work as we passed an Int not a string
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, isThat 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.
You may try :
String result = extras.get("id1");
try:
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)
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