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
In Java, there is no operator to create a copy of an object. Unlike C++, in Java, if we use the assignment operator then it will create a copy of the reference variable and not the object.
Parcelable is a serialization mechanism provided by Android to pass complex data from one activity to another activity.In order to write an object to a Parcel, that object should implement the interface “Parcelable“.
You can also define copy constructor if your class has mostly mutable properties. Utilize Object clone() method by calling super. clone() in overridden clone method, then make necessary changes for deep copying of mutable fields. If your class is serializable, you can use serialization for cloning.
There is a shorter way:
Foo foo1 = new Foo("a", "b", "c");
Parcel p = Parcel.obtain();
p.writeValue(foo1);
p.setDataPosition(0);
Foo foo2 = (Foo)p.readValue(Foo.class.getClassLoader());
p.recycle();
I had the same problem and here is my solution:
Parcel p = Parcel.obtain();
foo.writeToParcel(p, 0);
p.setDataPosition(0); // <-- this is the key
Foo foo2 = Foo.CREATOR.createFromParcel(p);
p.recycle();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With