Java Question

Storing and retrieving enums in SQLite with Java

I am in the need of being able to store and retrieve enums from a SQLite database, which I have solved with combined use of a wrapper class and enums, but I feel it's very poorly designed.

Every time I want to add a new item to the list of enums, I have to add it in three different places.

The enum must contain:

  • an int (or string) to represent it

  • a text string giving further text about the enum itself

  • a method to somehow restore its state from the database

Currently it is implemented like this:

public class items
public enum types {

private final int _value;
types(int value){_value = value;}
public int value(){return _value;}

public static types Get(int i)
case 0:
return types.FOO;
case 1:
return types.BAR;
case 2:
return types.BAZ;
return null;

public static String Get(Typer type)
case FOO:
return "This is foo!";
case BAR:
return "This is bar!";
case BAZ:
return "This is baz!";
return "No good!";

Is there a better way to handle this?

kan kan

An enum value has FOO.ordinal() function is a numeric representation of a value. The function returns its number between zero and n-1 where n - how much enum values do you have. Then you could use types.values()[i] to retrieve back a value by the number. But you should keep in mind that it's not allowed to reorder or add new enum in the middle, because the numbers will be changed.

Also, you could use types.valueOf("FOO") and for a string representation of the enum value. It's safer to use, because it doesn't depend on the declaration order.