The Wayback Machine - https://web.archive.org/web/20240905194349/https://www.geeksforgeeks.org/bundle-in-android-with-example/
Open In App

Bundle in Android with Example

Last Updated : 05 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

It is known that Intents are used in Android to pass to the data from one activity to another. But there is one another way, that can be used to pass the data from one activity to another in a better way and less code space ie by using Bundles in Android. Android Bundles are generally used for passing data from one activity to another. Basically here concept of key-value pair is used where the data that one wants to pass is the value of the map, which can be later retrieved by using the key. Bundles are used with intent and values are sent and retrieved in the same fashion, as it is done in the case of Intent. It depends on the user what type of values the user wants to pass, but bundles can hold all types of values (int, String, boolean, char) and pass them to the new activity.

The following are the major types that are passed/retrieved to/from a Bundle:

putInt(String key, int value), getInt(String key, int value)

putString(String key, String value), getString(String key, String value)

putStringArray(String key, String[] value), getStringArray(String key, String[] value)

putChar(String key, char value), getChar(String key, char value)

putBoolean(String key, boolean value), getBoolean(String key, boolean value)

Using the Bundle in the Android App

The bundle is always used with Intent in Android. Now to use Bundle writes the below code in the MainActivity.

Java




// creating a intent
Intent intent = new Intent(this, SecondActivity.class);
 
// creating a bundle object
Bundle bundle = new Bundle();
 
// storing the string value in the bundle
// which is mapped to key
bundle.putString("key1", "GFG :- Main Activity");
 
// passing the bundle into the intent
intent.putExtras(bundle);
 
// starting the intent
startActivity(intent);


Kotlin




// creating the instance of the bundle
val bundle = Bundle()
 
// storing the string value in the bundle
// which is mapped to key
bundle.putString("key1", "Gfg :- Main Activity")
 
// creating a intent
intent = Intent(this@MainActivity, SecondActivity::class.java)
 
// passing a bundle to the intent
intent.putExtras(bundle)
 
// starting the activity by passing the intent to it.
startActivity(intent)


 

 

Now create another empty activity named SecondActivity. Now to retrieve the data stored in the Bundle, write the following code in SecondActivity.

 

Java




// getting the bundle back from the android
Bundle bundle = getIntent().getExtras();
 
// getting the string back
String title = bundle.getString("key1", "Default");


Kotlin




// getting the bundle back from the android
val bundle = intent.extras
 
// performing the safety null check
var s:String? = null
 
// getting the string back
s = bundle!!.getString("key1", "Default"))


 

 

Alternatively, if one does not want to use the default value too, one can do this but remember it gives an exception.

 

For eg: boolean b = bundle.getBoolean(“pass the key here”);

 

 

If there exists no mapping corresponding to the key, it may lead to NullPointerException. Hence it’s recommended to add default values for the Bundle.

 

Example

 

Step 1: Create a new project

 

  1. Click on File, then New => New Project.
  2. Choose Empty activity
  3. Select language as Java/Kotlin
  4. Select the minimum SDK as per your need.

Step 2: Working with the activity_main.xml file

 

Now add two Buttons into the app, one button will pass the data which is stored into the bundle, and another button will pass the empty bundle, ie clearing the bundle with bundle.clear() and then passing the Bundle to Intent. The complete code for the activity_main.xml file is given below. Here one can see that the first button is used to pass the non-empty bundle, while the second button is used to pass the empty bundle.

 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity">
 
    <Button
        android:id="@+id/btnPassBundles"
        android:layout_width="275dp"
        android:layout_height="101dp"
        android:layout_marginTop="250dp"
        android:text="Pass Data Into Bundle"
        android:textSize="24sp"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <Button
        android:id="@+id/btnNoPassBundle"
        android:layout_width="277dp"
        android:layout_height="92dp"
        android:layout_marginBottom="220dp"
        android:layout_marginTop="75dp"
        android:text="Pass No Data/Empty BUNDLE"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnPassBundles" />
   
</androidx.constraintlayout.widget.ConstraintLayout>


 

 

Step 3: Create another activity and named it as SecondActivity

 

Now create another empty activity names SecondActivity. Follow the procedure illustrated in the image given below to create another activity.

 

SecondActivity

 

Step 4: Working with the activity_second.xml file

 

In this file add a TextView to display the text in the SecondActivity.

 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity">
 
    <TextView
        android:id="@+id/txtString"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="348dp"
        android:text="String from MainActivity"
        android:textSize="40sp"
        android:textStyle="bold"
        android:gravity="center"
        android:textColor="#008000"
        app:layout_constraintHorizontal_bias="0.428"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
</androidx.constraintlayout.widget.ConstraintLayout>


 

 

Step 5: Working with the MainActivity file

 

The complete code for the MainActivity is given below. Comments are added to understand the code easily.

 

Java




import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    Button btnPassBundles, btnNoPassBundle;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        btnPassBundles = findViewById(R.id.btnPassBundles);
        btnNoPassBundle = findViewById(R.id.btnNoPassBundle);
         
        // one button will pass the bundle and other button
        // will not pass the bundle
        btnPassBundles.setOnClickListener(this);
        btnNoPassBundle.setOnClickListener(this);
    }
 
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnPassBundles:
                // creating a bundle instance
                Bundle bundle = new Bundle();
                // passing the data into the bundle
                bundle.putString(
                        "key1",
                        "Passing Bundle From Main Activity to 2nd Activity");
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                // passing the bundle to the intent
                intent.putExtras(bundle);
                // starting the activity by passing the intent
                // to it.
                startActivity(intent);
                break;
                 
            case R.id.btnNoPassBundle:
                bundle = new Bundle();
                bundle.putString(
                        "key1",
                        "Not passing Bundle From Main Activity");
                // clearing the data stored into the bundle
                bundle.clear();
                // passing the intent to the second activity
                intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
        }
    }
}


Kotlin




import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
 
class MainActivity : AppCompatActivity(), View.OnClickListener {
   
    var btnPassBundles: Button? = null
    var btnNoPassBundle: Button? = null
   
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btnPassBundles = findViewById(R.id.btnPassBundles)
        btnNoPassBundle = findViewById(R.id.btnNoPassBundle)
         
        // one button will pass the bundle and other button
        // will not pass the bundle
        btnPassBundles?.setOnClickListener(this)
        btnNoPassBundle?.setOnClickListener(this)
    }
 
    override fun onClick(view: View) {
        when (view.id) {
            R.id.btnPassBundles -> {
                // creating the bundle instance
                val bundle = Bundle()
                // passing the data into the bundle
                bundle.putString("key1", "Passing Bundle From Main Activity to 2nd Activity")
                
                val intent = Intent(this@MainActivity, SecondActivity::class.java)
                intent.putExtras(bundle)
                startActivity(intent)
            }
             
            R.id.btnNoPassBundle -> {
                val bundle = Bundle()
                bundle.putString("key1", "Not passing Bundle From Main Activity")
                // clearing the bundle
                bundle.clear()
                // passing the intent to the second activity
                intent = Intent(this@MainActivity, SecondActivity::class.java)
                // passing the bundle into the intent
                intent.putExtras(bundle)
                startActivity(intent)
            }
        }
    }
}


 

 

Step 6: Working with the SecondActivity file

 

The complete code for the SecondActivity is given below. Comments are added to understand the code easily.

 

Java




import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
 
public class SecondActivity extends AppCompatActivity {
     
    TextView txtString;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
       
        txtString = findViewById(R.id.txtString);
       
          // getting the bundle from the intent
        Bundle bundle = getIntent().getExtras();
       
        // setting the text in the textview
        txtString.setText(bundle.getString("key1", "No value from the MainActivity"));
    }
}


Kotlin




import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
 
class SecondActivity : AppCompatActivity() {
   
    var txtString: TextView? = null
   
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
         
        txtString = findViewById(R.id.txtString)
        txtBoolean = findViewById(R.id.txtBoolean)
         
        // getting the bundle from the intent
        val bundle = intent.extras
       
        // setting the text in the textview
        txtString?.setText(bundle!!.getString("key1", "No value from MainActivity :("))
    }
}


 
 

Output: Run on Emulator

 



Previous Article
Next Article

Similar Reads

Spring - Resource Bundle Message Source (i18n)
A software is a multi purpose usage one. By using Message Source, it can be applicable to all languages. That concept is called i18n, that is according to the user locality, dynamic web pages are rendered in the user screen. We need to keep all the constants in a separate properties file which matches to each and every locality. In this article, le
5 min read
JSTL Formatting &lt; fmt:bundle &gt; Tag
In JSTL the &lt;fmt:bundle&gt; tag is mainly used to reference and format messages from the resource bundles. This tag allows us to get localized messages based on the user's locale. The main difference between &lt;fmt:setBundle&gt; and &lt;fmt:bundle&gt; is that, the &lt;fmt:setBundle&gt; sets the resource bundle for the entire page whereas the
3 min read
How to Use Fast Android Networking Library in Android with Example?
In Android, we know multiple networking libraries like Retrofit, Volley. We use these libraries specifically for making networking requests like performing actions on API. But Besides that, there is another library called Fast Networking Library which has a few advantages over other libraries. In this tutorial, we will be specifically focusing on l
4 min read
Android Jetpack - WorkManager with Example
WorkManager is an Android Jetpack library that provides a flexible and efficient way to schedule and manage background tasks in your app. It is a powerful and recommended tool for managing background processing in Android applications. With WorkManager, you can schedule asynchronous, deferred, and periodic tasks that need to run even when the app i
5 min read
Android BottomSheet Example in Kotlin
The Bottom Sheet is seen in many of the applications such as Google Drive, Google Maps and most of the applications used the Bottom Sheet to display the data inside the application. In this article, we will take a look at implementing a Bottom Sheet in the Android app using Kotlin in Android Studio. What is Bottom Sheet? Bottom Sheet is a component
5 min read
Spinner in Android with Example
Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the currently selected value and by using Adapter we ca
4 min read
ImageView in Android with Example
ImageView class is used to display any kind of image resource in the android application either it can be android.graphics.Bitmap or android.graphics.drawable.Drawable (it is a general abstraction for anything that can be drawn in Android). ImageView class or android.widget.ImageView inherits the android.view.View class which is the subclass of Kot
4 min read
PhotoView in Android with Example
In this article, PhotoView is added to android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifying the application when the user taps on the photo or when the displayed matrix gets changed. It provides smooth scroll
2 min read
NestedScrollView in Android with Example
NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. It is enabled by default. NestedScrollView is used when there is a need for a scrolling view inside another scrolling view. You have seen this in many apps for example when we open a pdf file and when
5 min read
Activity State Changes In Android with Example
Prerequisites: Activity lifecycle in android As it is known that every Android app has at least one activity associated with it. When the application begins to execute and runs, there are various state changes that activity goes through. Different events some user-triggered and some system triggered can cause an activity to do the transition from o
6 min read
Floating Action Button (FAB) in Android with Example
The floating action button is a bit different button from the ordinary buttons. Floating action buttons are implemented in the app's UI for primary actions (promoted actions) for the users and the actions under the floating action button are prioritized by the developer. For example the actions like adding an item to the existing list. So in this a
8 min read
Theming Floating Action Buttons in Android with Example
Prerequisite: Floating Action Button (FAB) in Android with ExampleExtended Floating Action Button in Android with Example Android application developers want to seek the attention of the users by customizing and theming the android application widgets and keep more traffic of customers only by the design of the application. In this article, it has
12 min read
ArrayAdapter in Android with Example
The Adapter acts as a bridge between the UI Component and the Data Source. It converts data from the data sources into view items that can be displayed into the UI Component. Data Source can be Arrays, HashMap, Database, etc. and UI Components can be ListView, GridView, Spinner, etc. ArrayAdapter is the most commonly used adapter in android. When y
3 min read
SlidingDrawer in Android with Example
SlidingDrawer is a common requirement in android mobiles to view the content whenever needed by sliding horizontally as well as vertically. In this article, let us check out Sliding Drawer which is used to hide the content out from the screen and allows the user to drag a handle to bring the content on the screen whenever needed in a very user-frie
9 min read
MVC (Model View Controller) Architecture Pattern in Android with Example
Developing an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in
8 min read
ViewStub in Android with Example
In Android, ViewStub is a zero-sized invisible View and very flexible in that we can lazily inflate layout resources at runtime. It is a dumb and lightweight view and it has zero dimension. Depending upon the requirement, whenever in need we can inflate at runtime. This is a classic example to handle when there are complicated views to be handled.
6 min read
MVP (Model View Presenter) Architecture Pattern in Android with Example
In the initial stages of Android development, learners do write codes in such a manner that eventually creates a MainActivity class which contains all the implementation logic(real-world business logic) of the application. This approach of app development leads to Android activity gets closely coupled to both UI and the application data processing
12 min read
Include and Merge Tags in Android with Example
Android apps are growing and one important aspect of it is reusability. Sometimes, the complexity of app design will be more and during that time, Android providing very efficient reusable features by means of the &lt;include/&gt; and &lt;merge/&gt; tags. Under &lt;merge/&gt; tags, we can specify a part of the layout that has to come in the main la
4 min read
Theming of Material Design EditText in Android with Example
Prerequisite: Material Design EditText in Android with Examples In the previous article Material Design EditText in Android with Examples Material design Text Fields offers more customization and makes the user experience better than the normal text fields. For example, Icon to clear the entire EditText field, helper text, etc. In this article, it'
4 min read
Theming Material Design Snackbars in Android with Example
In the previous article, it's been discussed Snackbar Material Design Components in Android. In this article, it's been discussed how we can theme material design Snackbar and increase the User Experience. Theming Example 1:This method is done using the styles.xml file. Where we need to override the default style of the Snackbar.Have a look at the
5 min read
RecyclerView using GridLayoutManager in Android With Example
RecyclerView is the improvised version of a ListView in Android. It was first introduced in Marshmallow. Recycler view in Android is the class that extends ViewGroup and implements Scrolling Interface. It can be used either in the form of ListView or in the form of Grid View. How to use RecyclerView as GridView? While implementing Recycler view in
6 min read
Fresco Image Loading Library in Android with Example
Fresco is one of the famous image loading libraries from URLs in Android. It is a powerful library for displaying and managing images from URLs. This library can load images from Users' devices, servers, and other local sources. The most important feature of this library is to show a placeholder image when the image from the URL takes so much time
3 min read
SimpleAdapter in Android with Example
In Android, whenever we want to bind some data which we get from any data source (e.g. ArrayList, HashMap, SQLite, etc.) with a UI component(e.g. ListView, GridView, etc.) then Adapter comes into the picture. Basically Adapter acts as a bridge between the UI component and data sources. Here Simple Adapter is one type of Adapter. It is basically an
7 min read
Interpolator in Android with Example
An interpolator is a function (in the mathematical sense) that outputs values "interpolated" between a range of values that are given to it as input. Interpolation is simply a method to generate new data points between two fixed data points. The exact values of these generated data points are determined by the kind of interpolation is performed. Fo
8 min read
CardView in Android With Example
CardView is a new widget in Android that can be used to display any sort of data by providing a rounded corner layout along with a specific elevation. CardView is the view that can display views on top of each other. The main usage of CardView is that it helps to give a rich feel and look to the UI design. This widget can be easily seen in many dif
3 min read
CardView using RecyclerView in Android with Example
RecyclerView is an extended version of ListView and GridView. It works on the ViewHolder design pattern. With the help of RecyclerView, we can add many extra features to our list of data. Before starting our example on the implementation of CardView in RecyclerView. We should know what CardView and RecyclerView mean. CardView: CardView is an extend
9 min read
Dagger 2 Android Example using Retrofit
Dagger 2 Android implementation is easier and it is based on Dependency Injection Architecture. Dependency Injection is a design pattern, which is a concept of Object-Oriented Programming, where we don’t create an object of another class inside a class using the new keyword (for Java). Instead, we supply the needed object from the outside. It is a
6 min read
Input Events in Android with Example
In Android, there's quite a method to intercept the events from a user's interaction with your application. When considering events within your interface, the approach is to capture the events from the precise View object that the user interacts with. The View class provides the means to try to do so. Within the varied View classes that you're goin
7 min read
TreeView in Android with Example
If you are looking for new UI designs to represent huge data, then there are so many ways to represent this type of data. You can use pie charts, graphs, and many more view types to implement these views. For displaying such huge data then we can prefer using a TreeView. TreeView is similar to that of a tree in which it has a parent node and inside
7 min read
ActionBar in Android with Example
In Android applications, ActionBar is the element present at the top of the activity screen. It is a salient feature of a mobile application that has a consistent presence over all its activities. It provides a visual structure to the app and contains some of the frequently used elements for the users. Android ActionBar was launched by Google in 20
8 min read
Article Tags :
Practice Tags :