简体   繁体   中英

Android Bundle is shares memory?

I using setArgument() / getArgument() for passing data from one fragment to another fragment.

I stored ArrayList into bundle using Bundle.putParcelableArrayList(), and I founded they - putted data and get data - are equals on memory.

Generally, I think, Parcelable source and regenerated(through CREATOR) instance is another instance, but they are same.

If Bundle shares memory, Why bundle has several methods for supports variety datatypes- Why not just passing Object instance or using generic on Bundle?

Why bundle has several methods for supports variety datatypes- Why not just passing Object instance or using generic on Bundle?

If the Bundle class would had only 1 method to pass objects , that would be horrible because that might cause confusion. Those variety datatypes method help the programmer to be sure of the kind of argument he/she want to get or put, Imagine this case where 4 programmers are working on a project and 1 programmer want to put an object in the Bundle instance (in this example imagine that the Bundle class has only 1 method to put objects (polymorphism))

Bundle bundle = new Bundle();
bundle.putObject("animal",new Dog());

And then later one of the programmer want to get that value and do this:

Bundle bundle = getArguments();
Cat variable = bundle.getObject("animal"); //This will cause an Exception, because the     argument it returned isn't a Cat class.

That's why Bundle class has those methods, to avoid this kind of errors.

Now the next answer is for the

or using generic on Bundle?

Generics was made to avoid the use of Casting, and to help programmers with the Collection Framework to avoid the kind of problem i described above.

public final class Bundle implements Parcelable, Cloneable {...} 

Bundle implements Parcelable, the system will automatically identify whether Bundle is a cross-process and cross-process if it is not, then the data is passed directly through shared memory, so this time you pass an object with the object to get is actually the same, but if it is cross-process, Parcelable interfaces to play a role in the cross-process, the system will call Parcelable's writeToParcel method, all data are converted into bytes, and then passed on to other processes, other processes received after, and then through the Parcelable Creator interface to restore data, restore data by Creator certainly is not the same instance. As for why there are so many ways Bundle, rather than directly using putObject (Object), getObject (), partly because Parcelable is required, not every type can parcel, then Bundle since realized Parcelable, must also be he needs to pass bundled data requirements are also supported parcel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM