I have been searching for a way to pass an object from one Activity to another. Different tutorials stated that the best way to do it is to make the class Parcelable. I've managed to implement it, but I have one question left.
There is a reference to another parcelable object (location
) inside the Office class. This tutorial tells to serialize it using dest.writeParcelable(location, flags);
and in.readParcelable(LatLng.class.getClassLoader());
, but the parcelabler created the code with dest.writeValue(location);
and then (LatLng) in.readValue(LatLng.class.getClassLoader());
.
I have checked and it worked both ways.
Could somebody please explain what is the difference between these two approaches? Is any of them better for some reasons? Thank you!
public class Office implements Parcelable {
@SuppressWarnings("unused")
public static final Parcelable.Creator<Office> CREATOR = new Parcelable.Creator<Office>() {
@Override
public Office createFromParcel(Parcel in) {
return new Office(in);
}
@Override
public Office[] newArray(int size) {
return new Office[size];
}
};
public final String name;
public final String address;
public final LatLng location;
public Office(String name, String address, LatLng location) {
this.name = name;
this.address = address;
this.location = location;
}
protected Office(Parcel in) {
name = in.readString();
address = in.readString();
// location = (LatLng) in.readValue(LatLng.class.getClassLoader());
location = in.readParcelable(LatLng.class.getClassLoader());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(address);
// dest.writeValue(location);
dest.writeParcelable(location, flags);
}
}
writeValue
is more generic, and since it takes an Object as parameter, internally they check the instanceOf
the object to call the specific method. If you know the type, I would stick with using the specific one
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