Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to put an Enum in a Bundle?

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

like image 799
zer0stimulus Avatar asked Jul 20 '10 18:07

zer0stimulus


People also ask

How do I assign an enum to a string?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

Can you inject an enum?

A perfectly functional method of injecting enum values in CDI. You will, however, need to make sure you know which type of enum you want to inject, and if you need multiple types, then you'll need to create qualifiers for each value.

Can enums be added?

No, it can't as this would mean that you would be able to modify existing types at runtime which you can't. Why you say you cant add values to an existing enum if the other answears are adding?


4 Answers

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");
like image 169
miguel Avatar answered Oct 21 '22 12:10

miguel


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);
like image 33
Alejandro Colorado Avatar answered Oct 21 '22 11:10

Alejandro Colorado


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");
like image 46
TheIT Avatar answered Oct 21 '22 13:10

TheIT


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))
like image 35
Vladislav Avatar answered Oct 21 '22 12:10

Vladislav