I am new to Android. Can you tell me what is a Bundle and how they are used in android?
Bundle generally use for passing data between various Activities. It depends on you what type of values you want to pass but bundle can hold all types of values and pass to the new activity.
You can use it like ...
Intent intent = new
Intent(getApplicationContext(),SecondActivity.class);
intent.putExtra("myKey",AnyValue);
startActivity(intent);
Now you can get the passed values by...
Bundle extras = intent.getExtras();
String tmp = extras.getString("myKey");
you can also find more info on android-using-bundle-for-sharing-variables and Passing-Bundles-Around-Activities
Copy from Here.
Read this:
http://developer.android.com/reference/android/os/Bundle.html
It can be used to pass data between different Activity's
Android using Bundle for sharing variables. Bundle is used to pass data between Activities. You can create a bundle, pass it to Intent that starts the activity which then can be used from the destination activity.
Here is Good Sample Example.
The Android developer reference overview states:
A mapping from String values to various Parcelable types.
IOW, a Bundle is a set of key/value pairs, where it implements an interface called Parcelable.
Unlike a C++ map, which is also a container of key/value pairs but all values are of the same type, a Bundle can contain values of different types.
Related
The are different ways how to pass data among components and apps in Android. For instance, here are some of them:
Intent intent = new Intent(this, DestinationActivity.class);
intent.putExtra("key", "value");
or
Bundle args = new Bundle();
args.putInt("someInt", someInt);
args.putParcelable("key", ParcelableObject);
Intent intent = new Intent();
intent.setAction("someAction");
intent.putExtra("key", arg);
or
fragment.setArguments(args);
As I know in java primitive values are stored in a stack and objects are placed in a heap. So, I would like to know what's happening when we call these methods: bundle.putInt(int) and bundle.putParcelable(Object), intent.putExtra("key", "string value") and fragment.setArguments(args) in Android.
Not all that much actually happens. Inside of Bundle is a Map. putInt will convert the integer primitive to an Integer object, and put the Integer into the map. putString will put the String object there. putParcelable will put an object that extends Parcelable into the map. That's all that happens at that time.
When startActivity is called, it will walk that map, and basically build a stream of data. The format isn't JSON but it serves a similar purpose- its a well understood format that can be parsed to values later on. As it walks that map, it knows how to add primitives (int, double, etc) to that file. It also knows how to do Strings. For Parcelable objects, there's a function in the object that adds the object to the stream and one to parse it out of the stream. It then takes that stream and asks the OS to pass that stream to the process that implements the intent. THe Android framework in that application will parse the stream back into a map (creating new objects) and then pass it to onCreate.
Why do all this work? Because the intent you run may not be in your process. So it can't share them directly, it needs to make copies. The extras is just a built in serialization method, making it easy to pass complex data.
Why do we sometimes use Bundle and sometimes Intent? Well, every Intent has a Bundle inside it. Calling intent.putIntExtra will call Bundle.putInt on the bundle inside that intent. Its just a convenience method so you don't need to call intent.getExtras().putInt().
I have the following code concerning Bundles in Android:
Bundle bundleFromIntent = getActivity().getIntent().getBundleExtra(Constants.CURRENCY);
bundleFromIntent.putParcelable(Constants.CURRENCY_ITEM, coin);
// convert the value after the refresh if the selected currency is not USD
if (!"USD".equals(savedCurrency.getCode())) {
coin.setLastPrice(200);
}
In the following example Coin initially has the the lastPrice value to 100.
I add that value to the bundleFromIntent .
What is strange is that after that addition, if I change the value from coin , the value in the Bundle also gets modified to 200 instead of 100 which is the value when I've added it to the Bundle.
Is this normal ? Why does the value added previously in the Bundle also get changed and when is the object added to the Bundle no longer able to be changed.
For the Coin object I am using Parceable.
If you check source code of Bundle class you would find the following implementation.
/* package */ ArrayMap<String, Object> mMap = null;
...
public void putParcelable(String key, Parcelable value) {
unparcel();
mMap.put(key, value);
mFdsKnown = false;
}
This means the object instance you added does not get written into a parcel, but is just stored into a map. Thus, if you modify a property of that instance, value gets changed.
Writing into a parcel happens later, when Intent gets sent, which is later in time. All changes you do to the instance will be applied to the instance stored in bundle too, because, in fact, this is the same instance.
Is this normal?
Yes.
Is this normal ?
Yes.
Why does the value added previously in the Bundle also get changed
Because it is the same object.
when is the object added to the Bundle no longer able to be changed.
You can change it whenever you want.
However, certain uses of an Intent, such as passing it to startActivity(), will result in inter-process communication (IPC). This will involve converting the Intent and its extras into a byte[] to pass to a core OS process. Even if the activity you are starting up is one of your own, that IPC still occurs, as will the IPC from the core OS process back to yours to have your desired activity start up. That process of converting the Intent into a byte[] and back into an Intent will result in a new Coin object being created, as part of creating the new Intent.
Not every use of Intent will have this effect -- notably, LocalBroadcastManager "broadcasts" do not make a new Intent and a new Coin. But if you start an activity, start or bind to a service, or send a broadcast, that involves IPC and will result in a new Coin being part of what the activity, service, or receiver gets.
A behaviour i'm observing w.r.t passing serializable data as intent extra is quite strange, and I just wanted to clarify whether there's something I'm not missing out on.
So the thing I was trying to do is that in ActivtyA I put a LinkedList instance into the intent I created for starting the next activity - ActivityB.
LinkedList<Item> items = (some operation);
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra(AppConstants.KEY_ITEMS, items);
In the onCreate of ActivityB, I tried to retrieve the LinkedList extra as follows -
LinkedList<Item> items = (LinkedList<Item>) getIntent()
.getSerializableExtra(AppConstants.KEY_ITEMS);
On running this, I repeatedly got a ClassCastException in ActivityB, at the line above. Basically, the exception said that I was receiving an ArrayList. Once I changed the code above to receive an ArrayList instead, everything worked just fine.
Now I can't just figure out from the existing documentation whether this is the expected behaviour on Android when passing serializable List implementations. Or perhaps, there's something fundamentally wrong w/ what I'm doing.
Thanks.
I can tell you why this is happening, but you aren't going to like it ;-)
First a bit of background information:
Extras in an Intent are basically an Android Bundle which is basically a HashMap of key/value pairs. So when you do something like
intent.putExtra(AppConstants.KEY_ITEMS, items);
Android creates a new Bundle for the extras and adds a map entry to the Bundle where the key is AppConstants.KEY_ITEMS and the value is items (which is your LinkedList object).
This is all fine and good, and if you were to look at the extras bundle after your code executes you will find that it contains a LinkedList. Now comes the interesting part...
When you call startActivity() with the extras-containing Intent, Android needs to convert the extras from a map of key/value pairs into a byte stream. Basically it needs to serialize the Bundle. It needs to do that because it may start the activity in another process and in order to do that it needs to serialize/deserialize the objects in the Bundle so that it can recreate them in the new process. It also needs to do this because Android saves the contents of the Intent in some system tables so that it can regenerate the Intent if it needs to later.
In order to serialize the Bundle into a byte stream, it goes through the map in the bundle and gets each key/value pair. Then it takes each "value" (which is some kind of object) and tries to determine what kind of object it is so that it can serialize it in the most efficient way. To do this, it checks the object type against a list of known object types. The list of "known object types" contains things like Integer, Long, String, Map, Bundle and unfortunately also List. So if the object is a List (of which there are many different kinds, including LinkedList) it serializes it and marks it as an object of type List.
When the Bundle is deserialized, ie: when you do this:
LinkedList<Item> items = (LinkedList<Item>)
getIntent().getSerializableExtra(AppConstants.KEY_ITEMS);
it produces an ArrayList for all objects in the Bundle of type List.
There isn't really anything you can do to change this behaviour of Android. At least now you know why it does this.
Just so that you know: I actually wrote a small test program to verify this behaviour and I have looked at the source code for Parcel.writeValue(Object v) which is the method that gets called from Bundle when it converts the map into a byte stream.
Important Note: Since List is an interface this means that any class that implements List that you put into a Bundle will come out as an ArrayList.
It is also interesting that Map is also in the list of "known object types" which means that no matter what kind of Map object you put into a Bundle (for example TreeMap, SortedMap, or any class that implements the Map interface), you will always get a HashMap out of it.
The answer by #David Wasser is right on in terms of diagnosing the problem. This post is to share how I handled it.
The problem with any List object coming out as an ArrayList isn't horrible, because you can always do something like
LinkedList<String> items = new LinkedList<>(
(List<String>) intent.getSerializableExtra(KEY));
which will add all the elements of the deserialized list to a new LinkedList.
The problem is much worse when it comes to Map, because you may have tried to serialize a LinkedHashMap and have now lost the element ordering.
Fortunately, there's a (relatively) painless way around this: define your own serializable wrapper class. You can do it for specific types or do it generically:
public class Wrapper <T extends Serializable> implements Serializable {
private T wrapped;
public Wrapper(T wrapped) {
this.wrapped = wrapped;
}
public T get() {
return wrapped;
}
}
Then you can use this to hide your List, Map, or other data type from Android's type checking:
intent.putExtra(KEY, new Wrapper<>(items));
and later:
items = ((Wrapper<LinkedList<String>>) intent.getSerializableExtra(KEY)).get();
If you are using IcePick library and are having this problem you can use Ted Hoop's technique with a custom bundler to avoid having to deal with Wrapper instances in your code.
public class LinkedHashmapBundler implements Bundler<LinkedHashMap> {
#Override
public void put(String s, LinkedHashMap val, Bundle bundle) {
bundle.putSerializable(s, new Wrapper<>(val));
}
#SuppressWarnings("unchecked")
#Override
public LinkedHashMap get(String s, Bundle bundle) {
return ((Wrapper<LinkedHashMap>) bundle.getSerializable(s)).get();
}
}
// Use it like this
#State(LinkedHashmapBundler.class) LinkedHasMap map
i want to know the usage of putExtra from very basic level
If you want add information to your intent you can use this method. This information is represented as tuple (key, value). There are the number of value types that can be included into the extras of intent (for instance, int, int[], Bundle, Parcelable, and so on). For each this method there is a corresponding "read" method that is used to get the information from the intent.
So here is a possible example how to use this. Imagine that you want explicitly call the activity B from activity A and pass to it an array of integers:
int intArray[] = {1,2,3,4};
Intent in = new Intent(this, B.class);
in.putExtra("my_array", intArray);
startActivity(in);
To read the information in activity B (in onCreate() method) you should use the following code:
Bundle extras = getIntent().getExtras();
int[] arrayInB = extras.getIntArray("my_array");
Add extended data to the intent.
The name must include a package prefix. For example, the app "com.android.contacts" would use names like "com.android.contacts.ShowAll".
Parameters:
name: The name of the extra data, with package prefix.
value: The double array data value.
Returns the same Intent object, for chaining multiple calls into a
single statement.
I have two activities A & B. In A i have three ArrayLists. I want to access these ArrayLists in activity B . How can I do that? These two activities are in same package.
To answer your question - which you could have easily found the answer to by searching stackoverflow - if you need to pass an ArrayList you can do like this:
ArrayList<String> list = new ArrayList<String>();
list.add("hello");
Bundle b = new Bundle();
b.putSerializable("myList", list);
Intent myIntent = new Intent(this, ActivityB.class);
myIntent.putExtras(b);
startActivity(myIntent);
And in ActivityB:
Intent myIntent = this.getIntent();
ArrayList<String> list = (ArrayList<String>) myIntent.getSerializableExtra("myList");
You probably can't access them directly. Usually only 1 Activity can be in the foreground. Trying to access elements in a background Activity (so like you lists in A from the acitve B) is a bad design choice.
I think you need to store the data from those lists in some shared location:
make them parcelable and store them in you app's preferences
store them in a SQLite db
pass them to Activity B via the starting Intent
Also, maybe you don't need to pass the whole lists to B, maybe you need only a part of them, consider that too.
* make them parcelable and store them in you app's preferences
* store them in a SQLite db
* pass them to Activity B via the starting Intent
It's wrong. Wrong I mean in a sense that no need to store Parcelable object in persistent storage, since as soon as you make object Parcelable - another Activity can get access to object without serialization (moreover serialization is not recommended). Android docs read:
Container for a message (data and object references) that can be sent through an IBinder. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC (using the various methods here for writing specific types, or the general Parcelable interface), and references to live IBinder objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel.
Parcel is not a general-purpose serialization mechanism. This class (and the corresponding Parcelable API for placing arbitrary objects into a Parcel) is designed as a high-performance IPC transport. As such, it is not appropriate to place any Parcel data in to persistent storage: changes in the underlying implementation of any of the data in the Parcel can render older data unreadable.