Using Enums with Parcelable

suggest change
/**
 * Created by Nick Cardoso on 03/08/16.
 * This is not a complete parcelable implementation, it only highlights the easiest 
 * way to read and write your Enum values to your parcel
 */
public class Foo implements Parcelable {

    private final MyEnum myEnumVariable;
    private final MyEnum mySaferEnumVariableExample;

    public Foo(Parcel in) {

        //the simplest way
        myEnumVariable = MyEnum.valueOf( in.readString() );

        //with some error checking
        try {
            mySaferEnumVariableExample= MyEnum.valueOf( in.readString() );
        } catch (IllegalArgumentException e) { //bad string or null value
            mySaferEnumVariableExample= MyEnum.DEFAULT;
        }

    }
    
    ...

    @Override
    public void writeToParcel(Parcel dest, int flags) {

        //the simple way
        dest.writeString(myEnumVariable.name()); 

        //avoiding NPEs with some error checking
        dest.writeString(mySaferEnumVariableExample == null? null : mySaferEnumVariableExample.name());

    }
    
}

public enum MyEnum {
    VALUE_1,
    VALUE_2,
    DEFAULT
}

This is preferable to (for example) using an ordinal, because inserting new values into your enum will not affect previously stored values

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents