Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use an enum with a switch case in Java?

Previously, I was saving the keys inside SharedPreferencesManager class using this way

public static final int KEY_COUNTRY_ID = 5,
     KEY_COUNTRY_NAME = 10,
     KEY_CURRENCY_ID = 15,
     KEY_CURRENCY_NAME = 20;

I decided to use an enum to store the keys because I think it is a better way than the old way, Here is what I tried.

SharedPreferencesManager.java

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class SharedPreferencesManager {

    private static SharedPreferences sharedPreferences;
    private static SharedPreferences.Editor editor;

    private static void initializeSharedPreferences(Context context) {
        if (sharedPreferences == null)
            sharedPreferences = context.getSharedPreferences("SharedPreferencesManager", Context.MODE_PRIVATE);
    }

    private static void initializeEditor() {
        if (editor == null)
            editor = sharedPreferences.edit();
    }

    public static void setValue(Context context, String key, int value) {
        initializeSharedPreferences(context);
        initializeEditor();
        editor.putInt(key, value);
        editor.apply();
    }

    public static int getIntegerValue(Context context, String key) {
        initializeSharedPreferences(context);
        switch (key) {
            case Keys.COUNTRY_ID.name():
            case Keys.CURRENCY_ID.name():
                return sharedPreferences.getInt(key, 5);
        }
        return -1;
    }

    public enum Keys {
        COUNTRY_ID,
        COUNTRY_NAME,
        CURRENCY_ID,
        CURRENCY_NAME
    }

}

The error

Constant expression required

The red lines under case Keys.COUNTRY_ID.name(): and case Keys.CURRENCY_ID.name():

How can I solve the problem?

>Solution :

As the compiler tells you, you need to use a constant String expression if you use switch(aStringVariable). The correct way to do this is to convert the String value to an enum constant and then use switch on that.

Convert the String to an enum instant using

Keys keyConstant = Keys.valueOf(key); //argument of "COUNTRY_ID" returns Keys.COUNTRY_ID

This looks up an enum constant by that name (matching the name()).
Then use it in the switch:

switch(keyConstant) {
  case COUNTRY_ID: ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading