Why would you put a new bundle in a new intent's extras vs setting extras directly on the new intent?

Viewed 281

New to Android here and am having a debate with a veteran over bundles and intents. This is what I've been doing...

Intent intent = new Intent(this, TargetActivity.class)
    .putExtra(Constants.BUNDLE_ITEM_A, itemA)
    .putExtra(Constants.BUNDLE_ITEM_B, itemB);

startActivity(intent);

He says that's wrong and you should be explicitly creating a new bundle, then passing it to 'putExtras', like so...

Intent intent = new Intent(this, TargetActivity.class);

Bundle bundle = new Bundle();
bundle.putSerializable(Constants.BUNDLE_ITEM_A, itemA);
bundle.putSerializable(Constants.BUNDLE_ITEM_B, itemB);
intent.putExtras(bundle);

startActivity(intent);

However,'putExtras' already create a new bundle internally, then just merges in the passed-in bundle, essentially meaning it's a throw-away object (for this use-case). Here's the source for 'putExtras'...

public Intent putExtras(Bundle extras) {
    if (mExtras == null) {
        mExtras = new Bundle();
    }
    mExtras.putAll(extras);
    return this;
}

...so it seems like his approach is redundant, and actually wasteful as it creates an unnecessary bundle allocation, just to have it unparceled and merged with the one already in the intent.

So am I missing something? Is there a technical reason to do it the way he suggests?

Note: I understand using 'putExtras' to pass around bundles that were handed to you. This however is creating a new bundle simply to insert in a new intent so it seems unnecessary to me, but I could be wrong. That's why I'm asking about technical benefits to his approach.

1 Answers

That's why I'm asking about technical benefits to his approach.

TL;TR: There's no benefit in the case you talk about. It's opposite.

Calling use of putExtra() wrong is rather plain silly, and quite exposes lack of knowledge of Intent internals. Your veteran should do quick look at Intent.java sources instead of blindly arguing as he'd then clearly see:

public Intent putExtras(Bundle extras) {
    if (mExtras == null) {
        mExtras = new Bundle();
    }
    mExtras.putAll(extras);
    return this;
}

and what is putAll() doing? Docs say:

Inserts all mappings from the given Bundle into this Bundle.

So putExtras() simply inserts all mappings from the Bundle given as argument into Intent's internal bundle.

It's pretty clear at that point that creating separate Bundle by hand, then stuffing all extras into it just to pass that bundle to putExtras() brings completely zero benefits over direct suffing with bunch of putExtra() calls.

putExtras() is simply a helper method to let you mass-set extras (hence its name) from i.e. bundle you received as method argument, so if you already have a bundle in hand which you want to pass along, you'd putExtras(), but if you stuffing things yourself, using putExtra() makes more sense.

Related