Domanda

I always thought that when I am passing custom parcelable object, by calling getParcelable(), it will return a totally new object. This is true when I am passing a parcelable object from one Activity to another Activity by putting that parcelable in the Bundle (Bundle is put in Intent).

But when I am trying to pass a parcelable object from a Activity to a background thread which has a Handler attach to, I don't get a new object which means if I modify the value of that object in the background thread, it will affect the object in Activity as well. How come? What have I done wrong?

This time the object is put in Bundle but the Bundle is put in Message, this is the only difference I can find when compare this to passing Parcelable between Activity.

//simple code sample, overwrite handleMessage() of Handler
public void handleMessage(Message msg) {
    SkCounter sc = msg.getData().getParcelable("abc");
    sc.testing = 99999; //if I change this value here, the object's value from Activity will change too. getParcelable() should create totally new object and changing value of it shouldn't affect other object, right? But how come this happens?
}

Anyone knows why?

È stato utile?

Soluzione

When passing a Bundle object from Activity to another Activity, Android framework will parcel and unparcel your object, the unparcel process will create a new object;

When passing a Bundle object through Message, Message.setData() just set the object, without doing parcel, so you are accessing the same object.

you can check Bundle source, your data is stored either in a Map or Parcel:

// Invariant - exactly one of mMap / mParcelledData will be null
// (except inside a call to unparcel)

/* package */ Map<String, Object> mMap = null;

/*
 * If mParcelledData is non-null, then mMap will be null and the
 * data are stored as a Parcel containing a Bundle.  When the data
 * are unparcelled, mParcelledData willbe set to null.
 */
/* package */ Parcel mParcelledData = null;

the Bundle.unparcel() method recreates your objects from Parcel.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top