4

I am using the parcel object to pass the value from one process to another. I want to create a clone of the parcel object but I am not able to use clone() method If anyone knows how to create the copy of parcel please provide the solution.

Brijesh Masrani
  • 1,439
  • 3
  • 16
  • 27

4 Answers4

18

The suggested solution is incomplete and will not work.

Here's a working solution:

(I have an object called message of type MessageDescriptor which I want to clone)

Parcel parcel = Parcel.obtain();
message.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
MessageDescriptor messageToBeSent = MessageDescriptor.CREATOR.createFromParcel(parcel);
parcel.recycle();
Lior
  • 7,845
  • 2
  • 34
  • 34
5

Assuming your object implements the Parcelable interface, you should be able to do the following:

SomethingParcelable myObject = new SomethingParcelable();

Parcel p = Parcel.obtain();
myObject.writeToParcel(p, 0);

//must be called after unmarshalling your data.
p.setDataPosition(0);

SomethingParcelable myClonedObject = SomethingParcelable.CREATOR.createFromParcel(p);
Nick Hamilton
  • 164
  • 11
Jeff Gilfelt
  • 26,131
  • 7
  • 48
  • 47
4

Another way to create a copy without accessing object specific CREATOR use following generic method.

 public <T extends Parcelable> T deepClone(T objectToClone) {
    Parcel parcel = null;
    try {   
        parcel = Parcel.obtain();
        parcel.writeParcelable(objectToClone, 0);
        parcel.setDataPosition(0);
        return parcel.readParcelable(objectToClone.getClass().getClassLoader());
    } finally {
        if (parcel != null) {
            parcel.recycle();
        }
    }
}
farhan patel
  • 1,490
  • 2
  • 19
  • 30
0

Also useful for copy constructors.

/**
 * Copy request passed in.
 *
 * @param request Request To clone, null is accepted, just creates a blank object
 */
public RealTimeJourneyPlanRequest(@Nullable RealTimeJourneyPlanRequest request) {
    if(request == null) return;
    // Only copy if the request past in is not null
    // Use the Parcel as its does deep cloning for us.
    final Parcel parcel = Parcel.obtain();
    request.writeToParcel(parcel, 0);
    parcel.setDataPosition(0);
    // Copy into this object
    readFromParcel(parcel);
    // Clean parcel back into object pool
    parcel.recycle();
}
Chris.Jenkins
  • 13,051
  • 4
  • 60
  • 61