Bundle of array of arraylist
How can I put an array of arrayList into a Bundle?
开发者_如何学CArrayList < myObjects >[] mElements;
Make YourObject
implement the Parcelable
interface, then use bundle.putParcelableArraylist(theParcelableArraylist)
.
Edit: whoops misread the question. Why do you want to save an array of arraylist? If its for persisting in an orientation change, maybe you want to use onRetainNonConfigurationInstance
instead?
Edit 2: Ok, here goes. Create a new Wrapper
class that implements Parcelable
(note that myObjects
also have to be parcelable). The writeToParcel
method will look something like this:
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mElements.length);
for(ArrayList<MyObject> element : mElements) {
dest.writeParcelableArray(element.toArray(new MyObject[0]), flags);
}
}
And the constructor:
private Wrapper(Parcel in) {
int length = in.readInt();
//Declare list
for (int i = 0; i < length; i++) {
MyObject[] read = in.readParcelableArray(Wrapper.class.getClassLoader());
//add to list
}
}
Not possible using bundle, as bundle allows arraylist of primitives only...
Try to use parcleable or application level data or static variable (bad practice).
If your objects support serialization, marked with the Serializable
interface, then you should be able to use bundle.putSerializable
.
ArrayList
supports Serializable
, but I'm not sure about a plain array
.
I just use putSerializable(myarraylistofstuff)
and then I get back with a cast using get()
, you just need to silence the unchecked warning. I suspect (correct me if wrong) you can pass any object faking it as Serializable
, as long you stay in the same process it will pass the object reference. This approach obviously does not work when passing data to another application.
EDIT: Currently android passes the reference only between fragment, I've tried to pass an arbitrary object to an Activity
, it worked but the object was different, same test using arguments of Fragment
showed same Object
instead.
Anyway it deserializes and serializes fine my Object
, if you have a lot of objects it's better to use Parcel
instead
精彩评论