Cheok Yan Cheng Cheok Yan Cheng - 1 month ago 33
Android Question

Save enum to SharedPreference

I was wondering, what is the common method being used to save

Enum
to
SharedPrefereces
? Currently, I'm using
gson
to convert enum to String, and then save it to
SharedPrefereces
.

Gson gson = new Gson();
// country is an enum.
String json_country = gson.toJson(country);
sharedPreferences.edit().putString(COUNTRY, json_country);


I was wondering, is this a good way? Is there any better way?

Answer

You can assotiate your enums with integers and store simple int, look this:

Cast Int to enum in Java (second answer) - also in same way you can do enumToInt