397

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

Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
zer0stimulus
  • 22,306
  • 30
  • 110
  • 141
  • 12
    In my opinion that advice from Google staff is bad. Enums are very convenient and suffering the described overhead is worthed. – ognian Jul 20 '10 at 18:24
  • 3
    can you revisit the answers and accept the 2nd one if you think it might be a better choice. – philipp Sep 06 '12 at 19:43
  • 6
    Under the heading "Avoiding Enums" in the above link it now says this: Performance Myths Previous versions of this document made various misleading claims. We address some of them here. – StackOverflowed Oct 02 '12 at 11:00
  • that section isn't even present anymore. – Nathaniel D. Waggoner Jan 30 '14 at 21:58
  • 1
    possible duplicate of [Passing enum or object through an intent (the best solution)](http://stackoverflow.com/questions/2836256/passing-enum-or-object-through-an-intent-the-best-solution) – pablisco Mar 03 '14 at 11:27

15 Answers15

833

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.get("key");

Intent:

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

// get
yourEnum = (YourEnum) intent.getSerializableExtra("key");
miguel
  • 16,205
  • 4
  • 53
  • 64
  • Is there something wrong with this method: saving: `outState.putSerializable("trollData", game.getFunkyTrolls());` loading: `game.setFunkyTrolls((Game.FunkyTroll[]) savedInstanceState.getSerializable("trollData"));` ? – Moberg May 22 '13 at 12:03
  • 24
    I would have voted for your answer, but the question was about adding the Enum to a Bundle and your reply explains how to add it to an Intent ... Granted it's almost the same thing, but Alejandro below fixed your answer. – Pooks Sep 27 '13 at 05:34
  • 2
    when using it with Bundle, it throws `ClassNotFoundException` – Display Name Mar 23 '14 at 20:28
  • 2
    this can be super slow and does not scale to arrays of things that contain enum, etc. See http://stackoverflow.com/a/5551155/175156 – yincrash Jun 18 '14 at 19:30
  • 1
    @yincrash enum uses custom serialization which is quite fast. Proof: http://docs.oracle.com/javase/1.5.0/docs/guide/serialization/spec/serial-arch.html#enum – Miha_x64 Aug 19 '17 at 10:14
  • If you're using Kotlin you can also add @parcelize to the enum class, and then use put/get parcelable. This has the advantage of being faster than serialization, but for most cases its probably not noticable – chris2112 Mar 06 '20 at 18:23
173

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);
Alejandro Colorado
  • 6,034
  • 2
  • 28
  • 39
  • 3
    Based on this: http://stackoverflow.com/questions/15521309/is-custom-enum-serializable-too, custom Enums are not serializable. So the custom fields in an Enum will not be serialized. How do you deal with this? – b.lyte Jan 08 '15 at 19:03
  • Nice question @clu! Maybe then you should think in passing it as a string as stated in http://stackoverflow.com/questions/609860/convert-from-enum-ordinal-to-enum-type/609879#609879 – Alejandro Colorado Jan 11 '15 at 02:07
  • @clu By not expecting custom fields to be serialised. It works fine if its just a normal enum like in the code above. – bluehallu Jan 11 '16 at 12:39
  • @AlejandroColorado what does this add to miguel 's answer? – tir38 May 17 '16 at 23:28
  • 1
    Miguel's answer was edited on 2015. The original answer said nothing about bundles, it only showed an example of an intent. – Alejandro Colorado May 17 '16 at 23:30
50

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");
TheIT
  • 11,919
  • 4
  • 64
  • 56
35

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))
Linh
  • 57,942
  • 23
  • 262
  • 279
Vladislav
  • 1,236
  • 13
  • 22
  • 6
    This is a good answer, but it can be complemented with a extension method, i use this one here: https://gist.github.com/Grohden/eea5ff9d5e3ba955aa2f57ff0df2683f – Gabriel Rohden Aug 23 '18 at 03:59
  • `.name` is very important path – Linh Oct 16 '18 at 09:15
  • This seems much simpler than turning the *Enum* into a parcelable, which would create further complexity if working with Android's *Room* database library. – AdamHurwitz Apr 08 '19 at 23:47
  • @GabrielDeOliveiraRohden, I'm not sure the extension method is needed as it seems to only avoid use of the `.name` in `putString()`. With Kotlin it's already streamlined if using `.apply`. **For example**: `ContentFragment.newInstance(Bundle().apply { putString(FEED_TYPE_KEY, SAVED.name) })` – AdamHurwitz Apr 08 '19 at 23:57
  • @AdamHurwitz, isn't the proposed extension function the entire point of Kotlins extension functions? It enforces you to not make mistakes, it's perfect! @GabrielDeOliveiraRohden 's link ```bundle.putEnum(key, enum) | bundle.getEnum<>(key)``` – Yokich Aug 15 '19 at 08:50
17

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

Community
  • 1
  • 1
user602359
  • 171
  • 1
  • 4
  • 1
    The ordering doesn't matter if the serialization->deserialization happens immediately at runtime, such as when calling from one activity to another. It could be a problem across processes such as sending Intents from one app to an older versions of the app. – miguel Jun 09 '16 at 05:27
6

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());
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Charlie Jones
  • 61
  • 1
  • 1
  • 1
    You can either use `putSerializable(key, value)`/`(Type) getSerializable(key)` or `putString(key, value.name())`/`Type.valueOf(getString(key))`, Parcelable implementation here is redundant and nonsensical. – Miha_x64 Aug 19 '17 at 10:17
  • 1
    Using `Parcelable` is a good solution to store Arrays of Enum-values. – RhodanV5500 Mar 21 '19 at 12:14
3

I've created a Koltin extension:

fun Bundle.putEnum(key: String, enum: Enum<*>) {
    this.putString( key , enum.name )
}

inline fun <reified T: Enum<T>> Intent.getEnumExtra(key:String) : T {
    return enumValueOf( getStringExtra(key) )
}

Create a bundle and add:

Bundle().also {
   it.putEnum( "KEY" , ENUM_CLAS.ITEM )
}

and get:

intent?.getEnumExtra< ENUM_CLAS >( "KEY" )?.let{}

Moises Portillo
  • 828
  • 8
  • 12
3

In Kotlin:

enum class MyEnum {
  NAME, SURNAME, GENDER
}

Put this enum in a Bundle:

Bundle().apply {
  putInt(MY_ENUM_KEY, MyEnum.ordinal)
}

Get enum from Bundle:

val ordinal = getInt(MY_ENUM_KEY, 0)
MyEnum.values()[ordinal]

Full example:

class MyFragment : Fragment() {

    enum class MyEnum {
        NAME, SURNAME, GENDER
    }

    companion object {
        private const val MY_ENUM_KEY = "my_enum_key"

        fun newInstance(myEnum: MyEnum) = MyFragment().apply {
            arguments = Bundle().apply {
                putInt(MY_ENUM_KEY, myEnum.ordinal)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        with(requireArguments()) {
            val ordinal = getInt(MY_ENUM_KEY, 0)
            val myEnum = MyEnum.values()[ordinal]
        }
    }
}

In Java:

public final class MyFragment extends Fragment {
    private static final String MY_ENUM_KEY = "my_enum";

    public enum MyEnum {
        NAME,
        SURNAME,
        GENDER
    }

    public final MyFragment newInstance(MyEnum myEnum) {
        Bundle bundle = new Bundle();
        bundle.putInt(MY_ENUM_KEY, myEnum.ordinal());
        MyFragment fragment = new MyFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = this.requireArguments();
        int ordinal = arguments.getInt(MY_ENUM_KEY, 0);
        MyEnum myEnum = MyEnum.values()[ordinal];
    }
}
vitiello.antonio
  • 323
  • 3
  • 12
2

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

Gotcha
  • 25
  • 1
  • 5
1

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?)
}
Rasoul Miri
  • 11,234
  • 1
  • 68
  • 78
0

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"));
Smalls
  • 352
  • 3
  • 13
0

This worked easily for me:

enum class MyEnum {
    FOO,
    BAR
}


val bundle = Bundle()
bundle.putAll(bundleOf("myKey", MyEnum.FOO))

// to read
val myEnum = bundle.get("myKey") as MyEnumClass

Note that if you get this from onCreate, you'll want to use as? to prevent any null exceptions.

Nick
  • 925
  • 1
  • 8
  • 13
0

enum YourEnum { TYPE1, TYPE2 }

Pass bunlde as bundleOf("TYPE" to YourEnum.TYPE1)

Receive as arguments?.let {it.getSerializable(B"TYPE") as YourEnum}

vishnuc156
  • 940
  • 12
  • 10
-1

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();
m3esma
  • 269
  • 3
  • 8
-1

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!

c0mmander
  • 77
  • 1
  • 6