Intent and Bundle Relation
While using Intent object we can put different types of data directly using its putExtra()
. We can also put these extra data into a Bundle
object and add it to Intent
. So why do we need Bundle
if we can do so using开发者_如何学Python Intent
directly?
As you can see, the Intent
internally stores it in a Bundle
.
public Intent putExtra(String name, String value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putString(name, value);
return this;
}
Sometimes you need to pass only a few variables
or values
to some Other Activity
, but what if you have a bunch of variable's or values
that you need to pass to various Activities
. In that case you can use Bundle
and pass the Bundle
to the required Activity
with ease. Instead of passing single variable's every time.
Let's assume you need to pass a Bundle
from one Activity
to another. That's why Intent
allows you to add Bundle
s as extra fields.
EDIT: For example if you want to pass a row from a database along with some other data it's very convenient to put this row into a Bundle
and add this Bundle
to the Intent
as a extra field.
I guess what @Lalit means is supposing your activity always passes the same variables to different intents, you can store all of them in a single Bundle
in your class and simply use intent.putExtras(mBundle)
whenever you need the same set of parameters.
That would make it easier to change the code if one of the parameters become obsolete in your code, for example. Like:
public class MyActivity {
private Bundle mBundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
mBundle = new Bundle();
mBundle.putString("parameter1", value1);
mBundle.putString("parameter2", value2);
}
private void openFirstActivity() {
Intent intent = new Intent(this, FirstActivity.class);
intent.putExtras(mBundle);
startActivity(intent);
}
private void openSecondActivity() {
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtras(mBundle);
startActivity(intent);
}
}
OBS: As stated already, Intent
stores the parameters in a internal Bundle
, and it's worth noting that when you call putExtras
, the internal Intent bundle doesn't point to the same object, but creates a copy of all variables instead, using a simple for
like this:
for (int i=0; i<array.mSize; i++) {
put(array.keyAt(i), array.valueAt(i));
}
精彩评论