Explain the Use of ‘Bundle’ in Android?

We use bundles to pass the required data to various subfolders.

In Android development, a Bundle is a data structure that is used to pass data between different components of an Android application, such as between activities. It acts as a container for carrying a set of key-value pairs, where the keys are strings and the values can be various types of data, such as primitive data types, Parcelable objects, or other Bundles.

Here are some common use cases for Bundles in Android:

  1. Activity Communication:
    • When you start a new activity, you can use a Bundle to pass data from one activity to another. The sending activity creates a Bundle, puts data into it using key-value pairs, and attaches it to the Intent before starting the new activity. The receiving activity then extracts the data from the Bundle.
      java
      // Sending activity
      Intent intent = new Intent(this, SecondActivity.class);
      Bundle bundle = new Bundle();
      bundle.putString("key_username", "JohnDoe");
      intent.putExtras(bundle);
      startActivity(intent);
      java
      // Receiving activity
      Bundle receivedBundle = getIntent().getExtras();
      if (receivedBundle != null) {
      String username = receivedBundle.getString("key_username");
      }
  2. Fragment Communication:
    • Similar to activities, Bundles can be used to pass data between fragments within the same activity.
  3. Saving and Restoring State:
    • Bundles are commonly used to save and restore the state of an Android component, such as an activity, during configuration changes (e.g., screen rotation). This ensures that important data is not lost when the device configuration changes.
      java
      @Override
      protected void onSaveInstanceState(Bundle outState) {
      outState.putString("key_username", "JohnDoe");
      super.onSaveInstanceState(outState);
      }
      java
      @Override
      protected void onRestoreInstanceState(Bundle savedInstanceState) {
      super.onRestoreInstanceState(savedInstanceState);
      String username = savedInstanceState.getString("key_username");
      }
  4. Inter-Component Communication:
    • Bundles can also be used to pass data between different components, such as services and activities.

In summary, Bundles play a crucial role in facilitating the transfer of data between various components in an Android application, aiding in communication and state management.