Passing enum or object through an intent (the best solution)

前端 未结 15 830
时光取名叫无心
时光取名叫无心 2020-12-04 05:41

I have an activity that when started needs access to two different ArrayLists. Both Lists are different Objects I have created myself.

Basically I need a way to pa

相关标签:
15条回答
  • 2020-12-04 06:03

    I think your best bet is going to be to convert those lists into something parcelable such as a string (or map?) to get it to the Activity. Then the Activity will have to convert it back to an array.

    Implementing custom parcelables is a pain in the neck IMHO so I would avoid it if possible.

    0 讨论(0)
  • 2020-12-04 06:03

    If you just want to send an enum you can do something like:

    First declare an enum containing some value(which can be passed through intent):

     public enum MyEnum {
        ENUM_ZERO(0),
        ENUM_ONE(1),
        ENUM_TWO(2),
        ENUM_THREE(3);
        private int intValue;
    
        MyEnum(int intValue) {
            this.intValue = intValue;
        }
    
        public int getIntValue() {
            return intValue;
        }
    
        public static MyEnum getEnumByValue(int intValue) {
            switch (intValue) {
                case 0:
                    return ENUM_ZERO;
                case 1:
                    return ENUM_ONE;
                case 2:
                    return ENUM_TWO;
                case 3:
                    return ENUM_THREE;
                default:
                    return null;
            }
        }
    }
    

    Then:

      intent.putExtra("EnumValue", MyEnum.ENUM_THREE.getIntValue());
    

    And when you want to get it:

      NotificationController.MyEnum myEnum = NotificationController.MyEnum.getEnumByValue(intent.getIntExtra("EnumValue",-1);
    

    Piece of cake!

    0 讨论(0)
  • 2020-12-04 06:06

    It may be possible to make your Enum implement Serializable then you can pass it via the Intent, as there is a method for passing it as a serializable. The advice to use int instead of enum is bogus. Enums are used to make your code easier to read and easier to maintain. It would a large step backwards into the dark ages to not be able to use Enums.

    0 讨论(0)
  • 2020-12-04 06:06

    Use Kotlin Extension Functions

    inline fun <reified T : Enum<T>> Intent.putExtra(enumVal: T, key: String? = T::class.qualifiedName): Intent =
        putExtra(key, enumVal.ordinal)
    
    inline fun <reified T: Enum<T>> Intent.getEnumExtra(key: String? = T::class.qualifiedName): T? =
        getIntExtra(key, -1)
            .takeUnless { it == -1 }
            ?.let { T::class.java.enumConstants[it] }
    

    This gives you the flexibility to pass multiple of the same enum type, or default to using the class name.

    // Add to gradle
    implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    
    // Import the extension functions
    import path.to.my.kotlin.script.putExtra
    import path.to.my.kotlin.script.getEnumExtra
    
    // To Send
    intent.putExtra(MyEnumClass.VALUE)
    
    // To Receive
    val result = intent.getEnumExtra<MyEnumClass>()
    
    0 讨论(0)
  • 2020-12-04 06:08

    Consider Following enum ::

    public static  enum MyEnum {
        ValueA,
        ValueB
    }
    

    For Passing ::

     Intent mainIntent = new Intent(this,MyActivity.class);
     mainIntent.putExtra("ENUM_CONST", MyEnum.ValueA);
     this.startActivity(mainIntent);
    

    To retrieve back from the intent/bundle/arguments ::

     MyEnum myEnum = (MyEnum) intent.getSerializableExtra("ENUM_CONST");
    
    0 讨论(0)
  • 2020-12-04 06:11

    You can make your enum implement Parcelable which is quite easy for enums:

    public enum MyEnum implements Parcelable {
        VALUE;
    
    
        @Override
        public int describeContents() {
            return 0;
        }
    
        @Override
        public void writeToParcel(final Parcel dest, final int flags) {
            dest.writeInt(ordinal());
        }
    
        public static final Creator<MyEnum> CREATOR = new Creator<MyEnum>() {
            @Override
            public MyEnum createFromParcel(final Parcel source) {
                return MyEnum.values()[source.readInt()];
            }
    
            @Override
            public MyEnum[] newArray(final int size) {
                return new MyEnum[size];
            }
        };
    }
    

    You can then use Intent.putExtra(String, Parcelable).

    UPDATE: Please note wreckgar's comment that enum.values() allocates a new array at each call.

    UPDATE: Android Studio features a live template ParcelableEnum that implements this solution. (On Windows, use Ctrl+J)

    0 讨论(0)
提交回复
热议问题