- Bundle in Android with Example
- Using the Bundle in the Android App
- Android Bundles
- Passing a Bundle on startActivity()?
- 5 Answers 5
- How to Iterate through all Bundle objects
- 2 Answers 2
- Android Bundle
- Android Tutorial
- Android Bundle
- Using Android Bundle
- Android Bundle Example Project Structure
- Android Bundle Example Code
Bundle in Android with Example
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.
Источник
Android Bundles
One way to save data when an Activity is destroyed is through the Bundle. This is just like the Intent you used earlier, in that it saves data in key/value pairs. Let’s set how the bundle works.
Have a look at the onCreate method again. The first line of the method is this:
protected void onCreate( Bundle savedInstanceState )
The Bundle part is a type, just like Int or String is a type. But this type handles keys and their values. The savedInstanceState part is just a variable name.
You can call various methods on your Bundle name. One of these methods is putInt. Another is putString. These methods are used to put data into a key/value pair. We want to save an integer value, so we could used this:
savedInstanceState.putInt( «HIGH_SCORE», someScore );
The key name we’ve come up with is HIGH_SCORE. The value for this key is whatever is inside of the variable called someScore.
Before our Activity is destroyed when the screen is rotated, Android allows you to override a method called onSaveInstanceState. This accepts a Bundle as a parameter.
Just below your displaySecondActivity method, add the following:
@override
public void onSaveInstanceState(Bundle mySavedInstanceState ) <
mySavedInstanceState.putInt( «HIGH_SCORE», someScore );
Your code should look like this:
We’ve given our Bundle the name mySavedInstanceState. This is then used to create the key/value pair. If Android destroys this Activity, then the method onSaveInstanceState is called. The first line is a call to the super class, which you must always do when Overriding a method. We then put our integer into the key called HIGH_SCORE.
We’re not quite done yet. We making sure to save data when the Activity is destroyed. But we’re not getting the data back anywhere. We can do that in the onCreate method.
When an app is first created, the savedInstanceState variable between the round brackets of onCreate will be null. It’s only not null when we start adding things to the Bundle object. We can test for this null state. Add this to you onCreate method, just before the final curly bracket:
if ( savedInstanceState != null ) <
someScore = savedInstanceState.getInt( HIGH_SCORE, 0 );
Your onCreate method should look like this:
To the left of an equal sign, we have our someScore variable. To the right, we’re calling a method on Bundle that has the name savedInstanceState. This method is getInt. This is used to get an integer value from the Bundle. If you had saved a string value then you’d use getString. In between the round brackets of getInt, we have the key name we set up, which was HIGH_SCORE. After a comma, you can type a default value, just in case something goes wrong. If it does, then the variable someScore will get a zero stored in it. If everything is OK, then getInt will grab the value associated with the HIGH_SCORE key.
Try it out. Run your app again. Click the button a few times and then rotate your device. Click the button again and you should find that the value in the Text View is incrementing properly, and not resetting to zero.
Exercise
You should also find that the Text View still says First Activity every time the device is rotated. You might want the number value displayed in the Text View at all times. Can you think of a way to fix this?
In the next lesson, we’ll take a look at the Android CardView.
Источник
Passing a Bundle on startActivity()?
What’s the correct way to pass a bundle to the activity that is being launched from the current one? Shared properties?
5 Answers 5
You have a few options:
1) Use the Bundle from the Intent:
2) Create a new Bundle
3) Use the putExtra() shortcut method of the Intent
Then, in the launched Activity, you would read them via:
NOTE: Bundles have «get» and «put» methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.
You can use the Bundle from the Intent:
Or an entire bundle:
Is this what you’re looking for?
Passing data from one Activity to Activity in android
An intent contains the action and optionally additional data. The data can be passed to other activity using intent putExtra() method. Data is passed as extras and are key/value pairs . The key is always a String. As value you can use the primitive data types int, float, chars, etc. We can also pass Parceable and Serializable objects from one activity to other.
Retrieving bundle data from android activity
You can retrieve the information using getData() methods on the Intent object. The Intent object can be retrieved via the getIntent() method.
Источник
How to Iterate through all Bundle objects
I am trying to create helper method that would iterate through all Bundle objects, in a generic manner.
By «generic» I mean:
- Doesn’t need to know the names (keys) of the objects in the Bundle passed as a parameter.
- Doesn’t need to change if another member (key) was added to the Bundle in the future.
So far, I figure out the following outline to accomplish that:
Does this approach make sense at all?
Is there a better way of accomplishing this?
2 Answers 2
Could you save everything as String using the toString() method? Don’t know if primitive types are mapped to their Object equivalents (e.g. int to class Integer), but if they are, then you might be able to do something like this, instead of laboriously checking each possible class.
Not sure if this would work for your needs, but I’m trying to do something similar to convert a bundle into a JSON string right now.
I would do it through reflection, if I were to do it at all. Store a static Map such that String.class maps to SharedPreference.putString(), etc. Then, when you’re looping through the items check their class against the map. If it doesn’t exist, check the superclass, etc. That will either give you the proper method to call or will let you know that the requested object’s type isn’t something that can be put into the preferences.
So the basic algorithm is:
- Get the object from the bundle
- Get its class
- See if the class is in the map
- If it is, invoke the specified method to put it in the SharedPreferences
- If it isn’t, get it’s superclass and return to step 3.
- If you get all the way up to java.lang.Object then you’ve got a bundled object that can’t immediately be stored in SharedPreferences. Depending on what classes you’ve hit along the way you might want to try to handle this as well or you might just want to record the error and move on. Without knowing why you’re doing this, it’s impossible to guess how you should react when the method fails. It invariably will unless you’ve got total control over both the bundle and the preferences, but if you’ve got that amount of control there’s no need to jump through all of these hoops because you could be much more straightforward and simply define your own keys.
Note: reflection isn’t fast and it isn’t the easiest thing to code and maintain. If at all possible I’d recommend finding a less generic method that fits your use case.
Источник
Android Bundle
Android Tutorial
In this tutorial, we’ll be discuss about android bundle to pass data between activities.
Android Bundle
Android Bundle is used to pass data between activities. The values that are to be passed are mapped to String keys which are later used in the next activity to retrieve the values.
Following are the major types that are passed/retrieved to/from a Bundle.
- putInt(String key, int value) , getInt(String key, int value)
- putIntArray(String key, int[] value) , getStringArray(String key, int[] value)
- putIntegerArrayList(String key, ArrayList value) , getIntegerArrayList(String key, ArrayList value value)
- putString(String key, String value) , getString(String key, String value)
- putStringArray(String key, String[] value) , getStringArray(String key, String[] value)
- putStringArrayList(String key, ArrayList value) , getStringArrayList(String key, ArrayList value value)
- putLong(String key, long value) , getLong(String key, long value)
- putLongArray(String key, long[] value) , getLongArray(String key, long[] value)
- putBoolean(String key, boolean value) , getBoolean(String key, boolean value)
- putBooleanArray(String key, boolean[] value) , getBooleanArray(String key, boolean[] value)
- putChar(String key, char value) , getChar(String key, char value)
- putCharArray(String key, char[] value) , getBooleanArray(String key, char[] value)
- putCharSequence(String key, CharSequence value) , getCharSequence(String key, CharSequence value)
- putCharSequenceArray(String key, CharSequence[] value) , getCharSequenceArray(String key, CharSequence[] value)
- putCharSequenceArrayList(String key, ArrayList value) , getCharSequenceArrayList(String key, ArrayList value value)
Using Android Bundle
A Bundle is passed in the following way.
Data from a Bundle is retrieved in the SecondActivity.java in the following manner.
If the key doesn’t map to any value, it may lead to NullPointerException. Hence it’s recommended to add null checks for the Bundle as well as the retrieved values.
Alternatively, we can set a default value too in case the mapped key doesn’t have any value.
To remove a value from the bundle the remove() method is passed with the relevant key as shown below.
To remove all data from the Bundle, the method clear() is called on the Bundle instance.
Android Bundle Example Project Structure
Android Bundle Example Code
The code for the activity_main.xml layout is given below.
The first button would pass a bundle with data into the SecondActivity.java while the second button would pass an empty bundle
The code for the activity_second.xml layout is given below.
The code for the MainActivity.java is given below.
The code for the SecondActivity.java is given below.
The output of the above application in action is given below.
Try passing in an ArrayList of any data type in the bundle and display them in a ListView in the next Activity!
This brings an end to android bundle tutorial. You can download the final Android Bundle Project from the link below.
Источник