Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing enums through aidl interfaces

As enums aren't primitive types, what's the most effective way to pass an enum through an aidl interface in Android? Is there a way to convert the enum to an ordinal first?

like image 727
Phillip Avatar asked Feb 08 '11 18:02

Phillip


2 Answers

I simply use

String enumString = myEnum.name() 

(with MyEnum as enum and myEnum as value) to get the String representation and then

MyEnum myEnum = MyEnum.valueOf(enumString) 

to reconstruct the enum from the String representation.

Using Ordinals may be a wee bit faster but if I may add Enums later, this is more likely to break old code.

//Edit: As I don't like to have String as return type, I now implemented Parcellable like mentioned here: Passing enum or object through an intent (the best solution)

import android.os.Parcel; import android.os.Parcelable;

enum InitResponse implements Parcelable {
// Everything is fine.
SUCCESS,
// Something else
FOO;


@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(final Parcel dest, final int flags) {
    dest.writeString(name());
}

public static final Creator<InitResponse> CREATOR = new Creator<InitResponse>() {
    @Override
    public InitResponse createFromParcel(final Parcel source) {
        return InitResponse.valueOf(source.readString());
    }

    @Override
    public InitResponse[] newArray(final int size) {
        return new InitResponse[size];
    }
};

}
like image 170
domenukk Avatar answered Sep 30 '22 15:09

domenukk


Non primitive types, other than String, require a directional indicator. Directional indicators include in, out and inout.

Take a look at the official documentation for that: http://developer.android.com/guide/developing/tools/aidl.html#aidlsyntax

Also, you can consider passing the String or ordinal representation of the enum and translate it back when needed. This is taken from the Effective Java 2nd edition:

// Implementing a fromString method on an enum type
private static final Map<String, Operation> stringToEnum = new HashMap<String, Operation>();
static { // Initialize map from constant name to enum constant
    for (Operation op : values())
        stringToEnum.put(op.toString(), op);
} // Returns Operation for string, or null if string is invalid
public static Operation fromString(String symbol) {
    return stringToEnum.get(symbol);
}

In the case above, Operation is an enum.


To get the ordinal of an enum consider this example:

public enum Badges{
    GOLD, SILVER, BRONZE;
}

// somewhere else:
int ordinal = Badges.SILVER.ordinal();// this should be 1
like image 44
Cristian Avatar answered Sep 30 '22 15:09

Cristian