Android: How to put an Enum in a Bundle?

AndroidEnumsAndroid Bundle

Android Problem Overview


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

Android Solutions


Solution 1 - Android

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");

Solution 2 - Android

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);

Solution 3 - Android

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");

Solution 4 - Android

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))

Solution 5 - Android

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: https://stackoverflow.com/questions/609860/convert-from-enum-ordinal-to-enum-type/609879#609879

Solution 6 - Android

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());
	}
}

Solution 7 - Android

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];
    }
}

Solution 8 - Android

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

Solution 9 - Android

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{}

Solution 10 - Android

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?)
}

Solution 11 - Android

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"));

Solution 12 - Android

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();

Solution 13 - Android

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionzer0stimulusView Question on Stackoverflow
Solution 1 - AndroidmiguelView Answer on Stackoverflow
Solution 2 - AndroidAlejandro ColoradoView Answer on Stackoverflow
Solution 3 - AndroidTheITView Answer on Stackoverflow
Solution 4 - AndroidVladislavView Answer on Stackoverflow
Solution 5 - Androiduser602359View Answer on Stackoverflow
Solution 6 - AndroidCharlie JonesView Answer on Stackoverflow
Solution 7 - Androidvitiello.antonioView Answer on Stackoverflow
Solution 8 - AndroidGotchaView Answer on Stackoverflow
Solution 9 - AndroidMoises PortilloView Answer on Stackoverflow
Solution 10 - AndroidRasoul MiriView Answer on Stackoverflow
Solution 11 - AndroidSmallsView Answer on Stackoverflow
Solution 12 - Androidm3esmaView Answer on Stackoverflow
Solution 13 - Androidc0mmanderView Answer on Stackoverflow