Junior
Where does the bundle come from and where does it go in Android?
sobes.tech AI
Answer from AI
A Bundle in Android is used to pass data between application components (such as Activity, Fragment, Service, BroadcastReceiver).
Where it comes from:
- From the creating component: The component that initiates interaction with another component creates a Bundle and fills it with data.
Where it goes:
- To the receiving component: The created Bundle is passed to the target component.
Examples of usage:
- When launching an Activity via Intent. Data is added to the Intent using
putExtra(), and then can be retrieved in the new Activity usinggetIntent().getExtras(). - When creating a Fragment and passing arguments to it. Data is added to a Bundle and set as arguments using
setArguments(). - When passing data between Activity and Service or BroadcastReceiver via Intent.
Example of passing data between Activities:
// Sending Activity
val intent = Intent(this, TargetActivity::class.java)
val bundle = Bundle()
bundle.putString("key_string", "hello")
bundle.putInt("key_int", 123)
intent.putExtras(bundle)
startActivity(intent)
// Receiving Activity (TargetActivity)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_target)
val bundle = intent.extras
if (bundle != null) {
val stringValue = bundle.getString("key_string")
val intValue = bundle.getInt("key_int")
// Use the received data
}
}