Dawid Hyży Dawid Hyży - 2 months ago 27
Android Question

Write enum with String to parcel

I had Parcelable enum like this:

public enum Option implements Parcelable {

DATA_BASE, TRIPS, BIG_PHOTOS,
OLD_PHOTOS, FILTERS_IMAGES,
CATEGORIES_IMAGES, PAGES,
SOUNDS, PUBLIC_TRANSPORT, MAPS;

public static final Parcelable.Creator<Option> CREATOR = new Parcelable.Creator<Option>() {

public Option createFromParcel(Parcel in) {
return Option.values()[in.readInt()];
}

public Option[] newArray(int size) {
return new Option[size];
}

};

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(ordinal());
}
}


Now I modified it and it looks like:

public enum Option implements Parcelable {

DATA_BASE("Database"), TRIPS("Trips"), BIG_PHOTOS("BigPhotos"),
OLD_PHOTOS("OldPhotos"), FILTERS_IMAGES("FiltersImages"),
CATEGORIES_IMAGES("CategoriesImages"), PAGES("Pages"),
SOUNDS("Sounds"), PUBLIC_TRANSPORT("PublicTransport"), MAPS("Maps");

private String option;

Option(String option){
this.option = option;
}

public String getName(){
return option;
}

public static final Parcelable.Creator<Option> CREATOR = new Parcelable.Creator<Option>() {

public Option createFromParcel(Parcel in) {
//...
}

public Option[] newArray(int size) {
//...
}

};

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel out, int flags) {
//...
}
}


How should I implement writeToParcel(), createFromParcel() and newArray() int this Enum? I need that to pass it through extra in intent.

Answer

I solved it by:

public enum Option implements Parcelable {

    DATA_BASE("Database"), TRIPS("Trips"), BIG_PHOTOS("BigPhotos"),
    OLD_PHOTOS("OldPhotos"), FILTERS_IMAGES("FiltersImages"),
    CATEGORIES_IMAGES("CategoriesImages"), PAGES("Pages"),
    SOUNDS("Sounds"), PUBLIC_TRANSPORT("PublicTransport"), MAPS("Maps");

    private String option;

    Option(String option){
        this.option = option;
    }

    public String getName(){
        return option;
    }

    private void setOption(String option){
        this.option = option;
    }

    public static final Parcelable.Creator<Option> CREATOR = new Parcelable.Creator<Option>() {

        public Option createFromParcel(Parcel in) {
            Option option = Option.values()[in.readInt()];
            option.setOption(in.readString());
            return option;
        }

        public Option[] newArray(int size) {
            return new Option[size];
        }

    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(ordinal());
        out.writeString(option);
    }
}
Comments