Sobes.tech
Junior

What can be passed to a Bundle object?

sobes.tech AI

Answer from AI

Primitive data types:

  • boolean
  • byte
  • short
  • int
  • long
  • float
  • double
  • char
  • String
  • CharSequence

Arrays of primitive data types:

  • boolean[]
  • byte[]
  • short[]
  • int[]
  • long[]
  • float[]
  • double[]
  • char[]
  • String[]
  • CharSequence[]

Objects implementing the Parcelable or Serializable interfaces.

Lists of objects implementing Parcelable or Serializable.

Bundle (i.e., you can put a Bundle inside a Bundle).

Some special Android data types:

  • SparseArray
  • Size
  • SizeF
  • Bundle (as mentioned above)

Example of saving data in a Bundle:

// Saving primitive types
bundle.putString("name", "Alice")
bundle.putInt("age", 30)

// Saving a Parcelable object (if MyParcelableObject implements Parcelable)
bundle.putParcelable("user", MyParcelableObject("Alice", 30))

// Saving a list of Parcelable objects
val users = arrayListOf(MyParcelableObject("Bob", 25), MyParcelableObject("Charlie", 35))
bundle.putParcelableArrayList("usersList", users)

// Saving a Serializable object (if MySerializableObject implements Serializable)
bundle.putSerializable("settings", MySerializableObject(true))

// Saving a Bundle inside a Bundle
val nestedBundle = Bundle()
nestedBundle.putString("extraInfo", "some data")
bundle.putBundle("nested", nestedBundle)

Example of retrieving data from a Bundle:

// Retrieving primitive types
val name = bundle.getString("name")
val age = bundle.getInt("age", 0) // with default value

// Retrieving a Parcelable object
val user = bundle.getParcelable<MyParcelableObject>("user")

// Retrieving a list of Parcelable objects
val usersList = bundle.getParcelableArrayList<MyParcelableObject>("usersList")

// Retrieving a Serializable object
val settings = bundle.getSerializable("settings") as? MySerializableObject

// Retrieving a nested Bundle
val nestedBundle = bundle.getBundle("nested")
val extraInfo = nestedBundle?.getString("extraInfo")
What can be passed to a Bundle object? — Android - sobes.tech