How to match int to enum

JavaAndroidEnumsAndroid Ndk

Java Problem Overview


I am receiving return value in the form of long or int from Native code in Android, which I want to convert or match with enum, for processing purpose. Is it possible ? How?

Java Solutions


Solution 1 - Java

If you have full control of values and enums, and they're sequential, you can use the enum ordinal value:

enum Heyo
{
  FirstVal, SecondVal
}

...later

int systemVal = [whatever];
Heyo enumVal = Heyo.values()[systemVal];

int againSystemVal = enumVal.ordinal();

Solution 2 - Java

You can set up your enum so it has the long or int built into it.

e.g: Create this file ePasswordType.java

public enum ePasswordType {

    TEXT(0),
    NUMBER(1);
    
    private int _value;
    
    ePasswordType(int Value) {
    	this._value = Value;
    }

    public int getValue() {
            return _value;
    }

    public static ePasswordType fromInt(int i) {
        for (ePasswordType b : ePasswordType .values()) {
            if (b.getValue() == i) { return b; }
        }
        return null;
    }
}

You can then access the assigned values like this:

ePasswordType var = ePasswordType.NUMBER;

int ValueOfEnum = var.getValue();

To get the enum when you only know the int, use this:

ePasswordType t = ePasswordType.fromInt(0);

Enums in java are very powerful as each value can be its own class.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSachchidanandView Question on Stackoverflow
Solution 1 - JavaKevin GalliganView Answer on Stackoverflow
Solution 2 - JavaKuffsView Answer on Stackoverflow