Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Parcel to clone an object?

Tags:

android

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

like image 964
user291701 Avatar asked Sep 22 '10 20:09

user291701


People also ask

How do you make a copy of an object in Java?

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.

What is parcelable in Android?

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“.

How do you copy an object in Java 8?

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.


2 Answers

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();
like image 63
user908643 Avatar answered Oct 14 '22 02:10

user908643


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();
like image 44
Larry McKenzie Avatar answered Oct 14 '22 00:10

Larry McKenzie