开发者

Android: How to put an Enum in a Bundle?

How do you add a开发者_开发知识库n Enum object to an Android Bundle?


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


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


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


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


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


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


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


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


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


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


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


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.


enum YourEnum { TYPE1, TYPE2 }

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

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


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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜