2

I've come across a problem with writing a collection of objects to parcel. I have a collection of MyObject (that is any object which implements Parcelable) stored inside MyRegistry that must be Pacelable as well:

public class MyObject implements Parcelable {...}

public class MyRegistry implements Parcelable {

  private List<Parcelable> mRegistry = new ArrayList<Parcelable>();

  ...

  public void writeToParcel(Parcel dest, int flags)
  {
    dest.writeParcelableArray((Parcelable[])mRegistry.toArray(), flags);
  }
}

However the ClassCastException is thrown when writeParcelableArray() is called. So what is wrong with writing MyObject(s) that is Parcelable? Haven't met any restrictions about this in the documentation...

Thank you in advance!

Paul E.
  • 1,889
  • 1
  • 12
  • 15

1 Answers1

2

I think it's because List.toArray() returns an Object[] array, which you then try to cast. You should instead use List.toArray(T[]).

gianpi
  • 3,110
  • 1
  • 17
  • 13
  • You're absolutely right! Thanks a lot! One more thing that is now unclear is ClassLoader parameter for readParcelableArray, at the other side. Registry class doesn't know the actual types of objects that are stored in it, they are just Parcelable... – Paul E. Dec 11 '11 at 20:49
  • Uff, the answer came from http://stackoverflow.com/questions/1996294/problem-unmarshalling-parcelables. I used ClassLoader from my application context: getContext().getClassLoader(). – Paul E. Dec 11 '11 at 21:05