Passing variables within Intents – Android

An easy way to pass variables between Activities is within the Intent. To do so you use something called a bundle.

Passing Variables

To get started, create you Intent as normal. Like so:

Intent intent = new Intent(getApplicationContext(), NewActivity.class);

The create something called a Bundle. Do so by writing:

Bundle bundle = new Bundle();

The next step is to add the variable onto the Bundle which you want to pass.

Place the name of the variable in speech marks and then add on the actual variable.

bundle.putInt("castingTotalForExtraExpenses",castingTotalForExtraExpenses);

After you have added all of the variables you want to pass, add the bundle onto the Intent.

intent.putExtras(bundle);

Then start the Intent as normal.

startActivity(intent);

Accessing Variables

To access the variable it is fairly simple.

First Declare a Bundle. Like so:

Bundle bundle1 = getIntent().getExtras();

The next step is to declare a variable the same as the kind of which you have passed.

int theTotalLeftToSpend = bundle1.getInt("castingTotalForExpenses");

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s