I’m trying to pass an int between two classes using a bundle. I have looked online and it seems like it should be easy to do, its just not working for me 🙁 any help is much appreciated! I am trying to pass the int life from one page to another in a simple game.
here is the code for the first page where I am passing it from
int life = 5;
....
if(input.equalsIgnoreCase(teststr))
{
Intent i = new Intent("com.name.PAGETWO");
i.putExtra("com.name.PAGETWO.life", life);
startActivity(i);
mpButtonClick.stop();
}
And on the second page, trying to receive the int
Intent i = new Intent("com.name.PAGETWO");
Bundle extras = i.getExtras();
int temp2 = extras.getInt("life");
int life = temp2;
when i try to run it, it tries to go on to the second page and then just says the application has unexpectedly stopped, but when i comment out the code it continues running as normal, so i know i am definitely putting in the code here wrong somewhere. thanks in advance!
You’re creating a brand new Intent on the second page, which of course doesn’t have the bundle. Instead, you need to retrieve the calling Intent using getIntent().
Here’s how your second page’s code could look:
EDIT: Looking at your code again, make sure the key name of the extra is consistent on both ends. To be sure, I usually use a final variable for this. So in your second activity (let’s say it’s
ActivityTwo), declare this at the top (outside ofonCreate()):Then in the calling activity:
(You may have also been constructing your Intent incorrectly; compare my example).
And in the second activity, inside of
onCreate():(You can replace
0with what you want the default value to be if the extra doesn’t exist.)That way you don’t have to worry about typos and can rely on Eclipse’s suggestions to make sure you’re consistent.