Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Brandon Schoonover
1,456 PointsHow to pass an integer between activities?
So I have two activities. MainActivity and Quiz. in MainAcitivity I use the random generator to get a random integer i call randomNumber.
I would like to then pass that randomNumber value into quiz.
Not sure how to do this....
2 Answers

Liam Peters
8,792 PointsHi Brandon, that is a perfectly valid way to do it, but this can be improved. You can pass in integers directly and retrieve them directly too. No need to go through strings!
//First Activity
Intent i = new Intent(this, SecondActivity.class);
i.putExtra("MY_KEY", 15);
startActivity(i);
//Second Activity
int number = getIntent().getExtras().getInt("MY_KEY");
Note that the first value in the putExtras()
method is just a unique identifier and you use the same key to retrieve your integer afterwards!

Brandon Schoonover
1,456 PointsI figured it out from stackoverflow/ http://developer.android.com/guide/components/intents-filters.html
If anyone else is interested:
In the 1stActivity, create a new Intent:
Intent i = new Intent(getApplicationContext(), NewActivity.class); i.putExtra("new_variable_name","value"); startActivity(i);
Then in the 2nd Activity, retrieve those values:
Bundle extras = getIntent().getExtras(); String value = extras.getString("new_variable_name");
Thomas Jaede
Courses Plus Student 7,633 PointsThomas Jaede
Courses Plus Student 7,633 PointsHi Brandon. If you post the code you're asking about, it is much more likely that someone will be able to help you.