Android
Enum
Bundle
Programming
Android Development

Android How to put an Enum in a Bundle?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Passing enums through Android Bundle objects is common when sending mode or state between activities and fragments. The safest approaches are Serializable or converting enum to a stable string. Choosing the right method depends on performance, refactor safety, and long-term compatibility.

Using Serializable Directly

Java and Kotlin enums are serializable by default, so this is the quickest method.

kotlin
1enum class ScreenMode {
2    VIEW,
3    EDIT,
4    PREVIEW
5}
6
7val bundle = Bundle().apply {
8    putSerializable("mode", ScreenMode.EDIT)
9}
10
11val mode = bundle.getSerializable("mode") as? ScreenMode ?: ScreenMode.VIEW
12println(mode)

This is easy but can be less efficient than primitive transport for frequent calls.

String-Based Approach for Stability

Storing enum name as string improves interoperability and can be safer across process recreation if handled carefully.

kotlin
1enum class ScreenMode {
2    VIEW,
3    EDIT,
4    PREVIEW
5}
6
7fun Bundle.putMode(key: String, mode: ScreenMode) {
8    putString(key, mode.name)
9}
10
11fun Bundle.getMode(key: String, default: ScreenMode = ScreenMode.VIEW): ScreenMode {
12    val raw = getString(key) ?: return default
13    return runCatching { ScreenMode.valueOf(raw) }.getOrDefault(default)
14}
15
16val b = Bundle()
17b.putMode("mode", ScreenMode.PREVIEW)
18println(b.getMode("mode"))

This pattern is explicit and resilient to missing values.

Fragment Arguments Example

Use argument bundles when creating fragments to keep initialization deterministic.

kotlin
1class DetailsFragment : Fragment() {
2    companion object {
3        private const val ARG_MODE = "arg_mode"
4
5        fun newInstance(mode: ScreenMode): DetailsFragment {
6            return DetailsFragment().apply {
7                arguments = Bundle().apply { putString(ARG_MODE, mode.name) }
8            }
9        }
10    }
11
12    private val mode: ScreenMode
13        get() {
14            val raw = requireArguments().getString(ARG_MODE) ?: ScreenMode.VIEW.name
15            return runCatching { ScreenMode.valueOf(raw) }.getOrDefault(ScreenMode.VIEW)
16        }
17}

This keeps parsing logic in one place.

Parcelable Alternative

For high-throughput navigation paths, Parcelable wrappers can be faster than Serializable, though more verbose. For simple enum-only transfer, string approach usually balances simplicity and safety.

Testing Enum Transport

Add quick round-trip tests for all enum values.

kotlin
1fun testEnumBundleRoundTrip() {
2    for (mode in ScreenMode.values()) {
3        val b = Bundle()
4        b.putMode("k", mode)
5        check(b.getMode("k") == mode)
6    }
7}
8
9testEnumBundleRoundTrip()

This catches accidental key or parsing regressions.

Intent Extras Pattern

The same enum transport options apply to intents between activities.

kotlin
1val intent = Intent(this, DetailsActivity::class.java).apply {
2    putExtra("mode", ScreenMode.EDIT.name)
3}
4startActivity(intent)
5
6// inside target activity
7val modeRaw = intent.getStringExtra("mode") ?: ScreenMode.VIEW.name
8val mode = runCatching { ScreenMode.valueOf(modeRaw) }.getOrDefault(ScreenMode.VIEW)

Using name values keeps intent payloads human-readable and easy to debug.

Refactor Safety Considerations

If enum constants are likely to be renamed, map stable wire values instead of using raw enum names.

kotlin
1enum class ScreenMode(val wire: String) {
2    VIEW("view"),
3    EDIT("edit"),
4    PREVIEW("preview");
5
6    companion object {
7        fun fromWire(raw: String): ScreenMode =
8            values().firstOrNull { it.wire == raw } ?: VIEW
9    }
10}

Wire-value mapping reduces breakage from refactors.

Parcelable for Composite Arguments

When passing enum together with other typed fields, a Parcelable argument object can improve clarity.

kotlin
@kotlinx.parcelize.Parcelize
data class DetailArgs(val mode: ScreenMode, val itemId: Long) : android.os.Parcelable

Use this for richer navigation contracts.

Practical Guidance

Keep one helper per key so reading and writing always use the same conversion rules. This avoids subtle bugs caused by mixed transport styles across screens.

Consistent argument helpers also improve onboarding and reduce navigation bugs in larger teams.

Common Pitfalls

  • Force casting serialized values without null checks.
  • Renaming enum constants without migration strategy.
  • Mixing string and serializable transport patterns inconsistently.
  • Reading arguments before fragment arguments are initialized.
  • Ignoring default values for corrupted or missing bundle data.

Summary

  • Enums can be stored in bundles with Serializable or string encoding.
  • String-based storage is explicit and robust for many apps.
  • Keep parse helpers centralized to avoid duplicate logic.
  • Provide safe defaults when reading bundle values.
  • Add round-trip tests for transport reliability.

Course illustration
Course illustration

All Rights Reserved.