Saltar al contenido principal

Bundle in Android

In Android development, passing data between activities or fragments is a common task. One of the ways to achieve this is by using a Bundle. A Bundle is a container that holds data as key-value pairs and can be passed between activities or fragments.

Creating a Bundle

To create a Bundle, simply call the Bundle constructor:

val bundle = Bundle()

Adding data to a Bundle

To add data to a Bundle, use the put methods. For example, to add a string:

bundle.putString("my_key", "my_value")

You can also add other types of data, such as integers:

bundle.putInt("my_int_key", 42)

Retrieving data from a Bundle

To retrieve data from a Bundle, use the get methods. For example, to retrieve a string:

val myValue = bundle.getString("my_key")

You can also retrieve other types of data, such as integers:

val myIntValue = bundle.getInt("my_int_key")

Passing a Bundle between activities

To pass a Bundle between activities, you can use the putExtras method on an Intent. For example:

val intent = Intent(this, MyActivity::class.java)
intent.putExtras(bundle)
startActivity(intent)

In the receiving activity, you can retrieve the Bundle using the getExtras method:

val bundle = intent.extras

Conclusion

In conclusion, Bundle is a useful tool for passing data between activities or fragments in Android development. It's simple to create and add data to a Bundle, and it can be easily passed between activities using an Intent.