Android: How to put an Enum in a Bundle?

前端 未结 12 1440
别那么骄傲
别那么骄傲 2020-12-22 16:56

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

12条回答
  •  不知归路
    2020-12-22 17:14

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

提交回复
热议问题