Sobes.tech
Junior

What is the purpose of the Bundle class in Android?

sobes.tech AI

Answer from AI

Bundle is used for passing data between application components such as Activity, Fragment, or Service.

Main functions:

  • Data storage: Can contain various primitive data types (int, boolean, String, etc.), arrays of primitives, as well as Parcelable or Serializable objects.
  • Key-value pairs: Data is stored as key-value pairs, where the key is a string.
  • State preservation: Used for saving and restoring the state of an Activity (for example, in onSaveInstanceState() and onRestoreInstanceState() methods).
  • Fragment arguments: Used to pass arguments to a Fragment via the setArguments() method.
  • Additional data in Intent: Allows passing additional data in an Intent using putExtra() and getExtras() methods.

Example of usage for passing data between Activities:

// Sending data from Activity A to Activity B
val intent = Intent(this, ActivityB::class.java)
val bundle = Bundle()
bundle.putString("username", "john.doe")
bundle.putInt("age", 30)
intent.putExtras(bundle)
startActivity(intent)

// Receiving data in Activity B
val extras = intent.extras
if (extras != null) {
    val username = extras.getString("username")
    val age = extras.getInt("age", -1) // Default value
}
What is the purpose of the Bundle class in Android… - sobes.tech