Android: How to put an Enum in a Bundle?

跟風遠走 提交于 2019-11-28 13:53:39

问题


How do you add an Enum object to an Android Bundle?


回答1:


Just pass it as int from ordinal(). Restore it from values[].




回答2:


Enums are Serializable so there is no issue.

Given the following enum:

enum YourEnum {
  TYPE1,
  TYPE2
}

Bundle:

// put
bundle.putSerializable("key", YourEnum.TYPE1);

// get 
YourEnum yourenum = (YourEnum) bundle. getSerializable("key");

Intent:

// put
intent.putSerializableExtra("key", yourEnum);

// get
yourEnum = (YourEnum) intent.getSerializableExtra("key");



回答3:


I know this is an old question, but I came with the same problem and I would like to share how I solved it. The key is what Miguel said: Enums are Serializable.

Given the following enum:

enum YourEnumType {
    ENUM_KEY_1, 
    ENUM_KEY_2
}

Put:

Bundle args = new Bundle();
args.putSerializable("arg", YourEnumType.ENUM_KEY_1);



回答4:


For completeness sake, this is a full example of how to put in and get back an enum from a bundle.

Given the following enum:

enum EnumType{
    ENUM_VALUE_1,
    ENUM_VALUE_2
}

You can put the enum into a bundle:

bundle.putSerializable("enum_key", EnumType.ENUM_VALUE_1);

And get the enum back:

EnumType enumType = (EnumType)bundle.getSerializable("enum_key");



回答5:


I use kotlin.

companion object {

        enum class Mode {
            MODE_REFERENCE,
            MODE_DOWNLOAD
        }
}

then put into Intent:

intent.putExtra(KEY_MODE, Mode.MODE_DOWNLOAD.name)

when you net to get value:

mode = Mode.valueOf(intent.getStringExtra(KEY_MODE))



回答6:


It may be better to pass it as string from myEnumValue.name() and restore it from YourEnums.valueOf(s), as otherwise the enum's ordering must be preserved!

Longer explanation: Convert from enum ordinal to enum type




回答7:


Another option:

public enum DataType implements Parcleable {
    SIMPLE, COMPLEX;

    public static final Parcelable.Creator<DataType> CREATOR = new Creator<DataType>() {

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

        @Override
        public DataType createFromParcel(Parcel source) {
            return DataType.values()[source.readInt()];
        }
    };

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.ordinal());
    }
}



回答8:


Use bundle.putSerializable(String key, Serializable s) and bundle.getSerializable(String key):

enum Mode = {
  BASIC, ADVANCED
}

Mode m = Mode.BASIC;

bundle.putSerializable("mode", m);

...

Mode m;
m = bundle.getSerializable("mode");

Documentation: http://developer.android.com/reference/android/os/Bundle.html




回答9:


For Intent you can use this way:

Intent : kotlin

FirstActivity :

val intent = Intent(context, SecondActivity::class.java)
intent.putExtra("type", typeEnum.A)
startActivity(intent)

SecondActivity:

override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState) 
     //...
     val type = (intent.extras?.get("type") as? typeEnum.Type?)
}



回答10:


One thing to be aware of -- if you are using bundle.putSerializable for a Bundle to be added to a notification, you could run into the following issue:

*** Uncaught remote exception!  (Exceptions are not yet supported across processes.)
    java.lang.RuntimeException: Parcelable encountered ClassNotFoundException reading a Serializable object.

...

To get around this, you can do the following:

public enum MyEnum {
    TYPE_0(0),
    TYPE_1(1),
    TYPE_2(2);

    private final int code;

    private MyEnum(int code) {
        this.code = navigationOptionLabelResId;
    }

    public int getCode() {
        return code;
    }

    public static MyEnum fromCode(int code) {
        switch(code) {
            case 0:
                return TYPE_0;
            case 1:
                return TYPE_1;
            case 2:
                return TYPE_2;
            default:
                throw new RuntimeException(
                    "Illegal TYPE_0: " + code);
        }
    }
}

Which can then be used like so:

// Put
Bundle bundle = new Bundle();
bundle.putInt("key", MyEnum.TYPE_0.getCode());

// Get 
MyEnum myEnum = MyEnum.fromCode(bundle.getInt("key"));



回答11:


A simple way, assign integer value to enum

See the following example:

public enum MyEnum {

    TYPE_ONE(1), TYPE_TWO(2), TYPE_THREE(3);

    private int value;

    MyEnum(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

}

Sender Side:

Intent nextIntent = new Intent(CurrentActivity.this, NextActivity.class);
nextIntent.putExtra("key_type", MyEnum.TYPE_ONE.getValue());
startActivity(nextIntent);

Receiver Side:

Bundle mExtras = getIntent().getExtras();
int mType = 0;
if (mExtras != null) {
    mType = mExtras.getInt("key_type", 0);
}

/* OR
    Intent mIntent = getIntent();
    int mType = mIntent.getIntExtra("key_type", 0);
*/

if(mType == MyEnum.TYPE_ONE.getValue())
    Toast.makeText(NextActivity.this, "TypeOne", Toast.LENGTH_SHORT).show();
else if(mType == MyEnum.TYPE_TWO.getValue())
    Toast.makeText(NextActivity.this, "TypeTwo", Toast.LENGTH_SHORT).show();
else if(mType == MyEnum.TYPE_THREE.getValue())
    Toast.makeText(NextActivity.this, "TypeThree", Toast.LENGTH_SHORT).show();
else
    Toast.makeText(NextActivity.this, "Wrong Key", Toast.LENGTH_SHORT).show();



回答12:


I think convert enum to int (for normal enum) and then set on bundle was been easiest way. like this code for intent:

myIntent.PutExtra("Side", (int)PageType.Fornt);

then for check state:

int type = Intent.GetIntExtra("Side",-1);
if(type == (int)PageType.Fornt)
{
    //To Do
}

but not work for all enum type!



来源:https://stackoverflow.com/questions/3293020/android-how-to-put-an-enum-in-a-bundle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!