- Grohden / BundleEnumExtension.kt
- Footer
- Android: How to put an Enum in a Bundle?
- Solution 3 — Android
- Solution 4 — Android
- Solution 5 — Android
- Solution 6 — Android
- Solution 7 — Android
- Solution 8 — Android
- Solution 9 — Android
- Solution 10 — Android
- Solution 11 — Android
- Solution 12 — Android
- Solution 13 — Android
- saschpe / BundleUtils.kt
- Footer
Grohden / BundleEnumExtension.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
import android.os.Bundle |
// Dunno if there’s a better way to extend both bundle and intents, but |
// you probably can extend intents in the same way |
fun Bundle. putEnum ( key : String , enum : Enum < * >) |
putString(key, enum.name) |
> |
inline fun < reified T : Enum < T >> Bundle. getEnum ( key : String ): T |
return enumValueOf(getString(key)) |
> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
enum class KotlinEnum |
KOTLIN_IS_LOVE |
> |
class MyClass : Fragment () |
companion object |
private const val ENUM_KEY = » ENUM_KEY « |
> |
// . some fragment declaration code |
fun newInstance ( ktEnum : KotlinEnum ) |
val args = Bundle () |
args.putEnum( ENUM_KEY , ktEnum) |
// Both way works |
val cEnum = args.getEnum( ENUM_KEY ) as KotlinEnum |
val dEnum = args.getEnum< KotlinEnum >( ENUM_KEY ) |
> |
> |
Just a quick quip, but maybe this instead.
inline fun > Bundle.getEnum(key: String, default: T): T < val found = getString(key) return if (found == null) < default >else enumValueOf(found) >
Then you if you can have e.g.:
. and the IDE doesn’t scream it’s lungs out 🙂
In case you want to use null instead of default you can also create an extension like this:
inline fun > Bundle.getEnum(key:String): T? < return getString(key)?.let < enumValueOf(it) > >
Footer
You can’t perform that action at this time.
Android: How to put an Enum in a Bundle?
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.
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.
You can put the enum into a bundle:
bundle.putSerializable("enum_key", EnumType.ENUM_VALUE_1);
EnumType enumType = (EnumType)bundle.getSerializable("enum_key");
Solution 4 — Android
companion object < enum class Mode < MODE_REFERENCE, MODE_DOWNLOAD >>
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!
Solution 6 — Android
public enum DataType implements Parcleable < SIMPLE, COMPLEX; public static final Parcelable.CreatorDataType> CREATOR = new CreatorDataType>() < @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
enum class MyEnum NAME, SURNAME, GENDER >
Put this enum in a Bundle:
Bundle().apply < putInt(MY_ENUM_KEY, MyEnum.ordinal) >
val ordinal = getInt(MY_ENUM_KEY, 0) MyEnum.values()[ordinal]
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] > > >
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");
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 > Intent.getEnumExtra(key:String) : T < return enumValueOf( getStringExtra(key) ) >
Bundle().also < it.putEnum( "KEY" , ENUM_CLAS.ITEM ) >
intent?.getEnumExtra< ENUM_CLAS >( "KEY" )?.let<>
Solution 10 — Android
For Intent you can use this way:
Intent : kotlin
val intent = Intent(context, SecondActivity::class.java) intent.putExtra("type", typeEnum.A) startActivity(intent)
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; > >
Intent nextIntent = new Intent(CurrentActivity.this, NextActivity.class); nextIntent.putExtra("key_type", MyEnum.TYPE_ONE.getValue()); startActivity(nextIntent);
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);
int type = Intent.GetIntExtra("Side",-1); if(type == (int)PageType.Fornt) < //To Do >
but not work for all enum type!
saschpe / BundleUtils.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
package saschpe.alphaplus.utils |
import android.os.Bundle |
inline fun < reified T : Enum < T >> Bundle. getEnum ( key : String , default : T ) = |
getInt(key). let < if (it >= 0 ) enumValues< T >()[it] else default > |
fun < T : Enum < T >> Bundle. putEnum ( key : String , value : T ? ) = |
putInt(key, value?.ordinal ? : — 1 ) |
package saschpe.alphaplus.utils import android.os.Bundle inline fun reified T : EnumT>> Bundle.getEnum(key: String, default: T) = getInt(key, -1).let < if (it >= 0) enumValuesT>()[it] else default > fun T : EnumT>> Bundle.putEnum(key: String, value: T?) = putInt(key, value?.ordinal ?: -1)
Should be with default value of -1 in getInt()
Footer
You can’t perform that action at this time.