12

I have this enum like this

  enum Status {READY, DISCONNECTED, RECEIVING, ... more }

I want to send a value of this enum over to another thread via a Bundle.

The other thread would like to extract enum value from the Bundle ,

How can this be done , smartly ?

   Bundle createBundle(Status status);

and

   Status getStatus(Bundle b);

Thanks,

Simon
  • 14,407
  • 8
  • 46
  • 61
Ahmed
  • 14,503
  • 22
  • 92
  • 150
  • You can't. Think of an enum as a shortcut way to create a class. It has no "instance" and it's therefore meaningless to bundle it. You could bundle the type and pass that but that doesn't give you anything. Are you perhaps wanting to pass an enum value? Actually, what *are* you trying to do? – Simon Nov 14 '12 at 18:38
  • Ah,. just seen the title. Please edit your question to make it explicit that you are trying to pass an enum value, not the enum itself, and accepts Todd's answer. Thanks! – Simon Nov 14 '12 at 18:41
  • Possible duplicate of [Android: How to put an Enum in a Bundle?](http://stackoverflow.com/questions/3293020/android-how-to-put-an-enum-in-a-bundle) – blahdiblah Mar 04 '15 at 22:07
  • Easier way: [Android: How to put an Enum in a Bundle?](http://stackoverflow.com/questions/3293020/android-how-to-put-an-enum-in-a-bundle/38764715#38764715) – m3esma Aug 04 '16 at 10:29

2 Answers2

35

Since Enum is serializable, we can just pack the enum into the bundle using:

public static String MY_ENUM = "MY_ENUM";
myBundle.putSerializable(MY_ENUM, enumValue);

To retrieve, use:

MyEnum myEnum = (MyEnum) myBundle.getSerializable(MY_ENUM);
mutexkid
  • 1,076
  • 1
  • 12
  • 12
14

Good question! I'm not aware of a way to pack enums directly. I always use this to pack:

int intValue = myEnum.ordinal();

then this to unpack:

MyEnum enumValue = MyEnum.values()[intValue];
Todd Sjolander
  • 1,459
  • 1
  • 15
  • 28