Android

Brandon Schoonover
Brandon Schoonover
1,241 Points

How 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....

Thomas Jaede
Thomas Jaede
Pro Student 7,585 Points

Hi Brandon. If you post the code you're asking about, it is much more likely that someone will be able to help you.

2 Answers

Brandon Schoonover
Brandon Schoonover
1,241 Points

I 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");

Hi 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!