Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `writeValue` and `writeParcelable`?

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);
    }
}
like image 959
Florin Avatar asked Oct 30 '22 17:10

Florin


1 Answers

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

like image 127
Blackbelt Avatar answered Nov 10 '22 18:11

Blackbelt