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?


Solution 1:

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:

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.