0

How can I put an array of arrayList into a Bundle?

ArrayList < myObjects >[] mElements;

4 Answers 4

4

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
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

It is mostly for orientation changes but I need it as well to accommodate the activity lifecycle.
I think you can create a wrapper class that implements parcelable and do it in a not so elegant way. I'll edit my answer.
1

Not possible using bundle, as bundle allows arraylist of primitives only...

Try to use parcleable or application level data or static variable (bad practice).

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.