android - Using Parcel to clone an object? -
i have class has implemented parcelable. can following create new instance of class?:
foo foo = new foo("a", "b", "c"); parcel parcel = parcel.obtain(); foo.writetoparcel(parcel, 0); foo foo2 = foo.creator.createfromparcel(parcel);
i'd foo2 clone of foo.
---------------------- update -------------------------------
the above not work (all foo members null in new instance). i'm passing foos between activities fine, parcelable interface implemented ok. using below 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 same foo1.
found following q: how use parcel in android?
this working ok, can go code, not sure if there's shorter way (other implementing copy constructor...).
thanks
there 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();
Comments
Post a Comment