![]() |
VOOZH | about |
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)
The bundle is always used with Intent in Android. Now to use Bundle writes the below code in the MainActivity.
Now create another empty activity named SecondActivity. Now to retrieve the data stored in the Bundle, write the following code in SecondActivity.
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.
Step 1: Create a new project
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.
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.
π SecondActivityStep 4: Working with the activity_second.xml file
In this file add a TextView to display the text in the SecondActivity.
Step 5: Working with the MainActivity file
The complete code for the MainActivity is given below. Comments are added to understand the code easily.
Step 6: Working with the SecondActivity file
The complete code for the SecondActivity is given below. Comments are added to understand the code easily.