Wednesday, 14 August 2013

Saving the content of an Enum in Shared preferences

The enum is very useful in java for switches. The value of it could be saved easily in the shared preferences of Android in order to be persistence.

Here are some trick to save it as String.

1. Implement a static method which use the valueOf with String

public enum MyEnum {
    ENUM1, ENUM2, ENUM3, ENUM4;

    public static MyEnum toMyEnum (String myEnumString) {
        try {
            return valueOf(myEnumString);
        } catch (Exception ex) {
                // For error cases
            return ENUM1;
        }
    }
}

2. Save it as String by calling the method toString()

public void setMyEnum(MyEnum myEnum) {
    editor.putString("MyEnum", myEnum.toString());
    editor.commit();
}

3. Get it as String and convert it as Enum

public MyEnum getMyEnum() {
    String myEnumString = sp.getString("MyEnum", MyEnum.ENUM1.toString());
    return MyEnum.toMyEnum(myEnumString);
}

4. Use it in the Switch

switch (getMyEnum()) {
case ENUM1: {
textView.setText("Enum1");
break;
}
case ENUM2: {
textView.setText("Enum2");
break;
}
case ENUM3: {
textView.setText("Enum3");
break;
}
case ENUM4: {
textView.setText("Enum4");
break;
}
}

Source code:

No comments:

Post a Comment