I have a class which has implemented Parcelable. Can I do something like the following to create a new instance of a class?:
Foo foo = new Foo("a", "b", "c");
Parcel parcel = Parcel.obtain();
foo.writeToParcel(parcel, 0);
Foo foo2 = Foo.CREATOR.createFromParcel(parcel);
I'd like foo2 to be a clone of foo.
---------------------- update -------------------------------
The above does not work (all Foo members are null in new instance). I'm passing Foos between activities just fine, so the Parcelable interface is implemented ok. Using the below which works:
Foo foo1 = new Foo("a", "b", "c");
Parcel p1 = Parcel.obtain();
Parcel p2 = Parcel.obtain();
byte[] bytes = null;
p1.writeValue(foo1);
bytes = p1.marshall();
p2.unmarshall(bytes, 0, bytes.length);
p2.setDataPosition(0);
Foo foo2 = (Foo)p2.readValue(Foo.class.getClassLoader());
p1.recycle();
p2.recycle();
// foo2 is the same as foo1.
found this from the following q: How to use Parcel in Android?
This is working ok, I can go with this but it is extra code, not sure if there's a shorter way to do it (other than properly implementing a copy constructor...).
Thanks