Intent and Bundle Relation

前端 未结 4 713
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 04:32

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 a

相关标签:
4条回答
  • 2020-12-10 05:08

    Let's assume you need to pass a Bundle from one Activity to another. That's why Intent allows you to add Bundles 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.

    0 讨论(0)
  • 2020-12-10 05:11

    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;
    }
    
    0 讨论(0)
  • 2020-12-10 05:29

    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.

    0 讨论(0)
  • 2020-12-10 05:30

    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));
    }
    
    0 讨论(0)
提交回复
热议问题