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.
Related
I'm trying to write a unit test for some Android code that looks for a specific key being present in an Intent object. As part of my test, I'm creating an Intent object and adding a String to it. However, when I use the below code, my variable is initalized to null:
val data = Intent().putExtra("key", "value")
// data is null
If I split this up into two lines, it works just fine:
val data = Intent()
data.putExtra("key", "value")
// data is non-null and contains my key/value
What feature of the Kotlin language is causing this to happen?
Note that putExtra() returns an Intent object. From the Android source:
public #NonNull Intent putExtra(String name, String value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putString(name, value);
return this;
}
In the first case, the inferred type is Intent!. I was under the impression that this just means that it's an Intent or an Intent? but Kotlin doesn't want to make devs go crazy with Java platform types. Still, given that putExtra() returns a non-null value, I'd expect the actual value of data to be non-null.
The short answer is what #CommonsWare and #TheWanderer mentioned in comments: my test class was in the test/ directory, so it was using a mock Intent implementation instead of the real thing.
When I move my test to the androidTest/ directory, everything works as expected. The observed behavior has nothing to do with Kotlin.
Some extra info about why this was so confusing...
First, I was mistaken when I wrote this:
val data = Intent()
data.putExtra("key", "value")
// data is non-null and contains my key/value
The data variable was non-null, but it did not actually contain my key/value pair. The mock Intent implementation I was using was dropping the putExtra() call.
So, why was my test passing?
The one particular test I decided to dig deeper on was testing the negative case (when a key other than the one it expects is present in the Intent). But I wasn't passing an Intent with the wrong key, I was passing an Intent with no keys at all. Either way, though, the expected key is not present, and the method returns false.
The positive case (where the required key actually was passed to putExtra()) failed with an AssertionError. Too bad I didn't pick this one to scrutinze.
My main project has apparently stubbed Intent.putExtra() as a no-op, via the returnDefaultValues = true gradle option. When I create a new project and try to reproduce this issue, I get a very clear error:
java.lang.RuntimeException: Method putExtra in android.content.Intent not mocked. See http://g.co/androidstudio/not-mocked for details.
at android.content.Intent.putExtra(Intent.java)
at com.example.stackoverflow.IntentTest.test(IntentTest.kt:12)
Unfortunately, with the mocked putExtra(), I never got this helpful message.
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'm making a program that requires transfer of data between Activities, I see the boolean array object I'm trying to transfer in MyIntent.mExtras.mMap, but when I do,
Intent.getBooleanArrayExtra("AnsweredBoolAR")
I get null. I'm using
Intent MyIntent = new Intent(MainActivity.this, DataSummary.class);
MyIntent.putExtra("AnsweredBoolAR", Answered.toArray());
to send my data.
I've used the debugger and the array that I'm putting into the key and value set isn't null.
When you use the toArray() method of ArrayList, it returns an array of Object[] rather than an array of the specific type contained by the ArrayList.
When you call getBooleanArrayExtra(...) on the Intent however, it will be looking specifically for boolean[] and returns null because it can't find an array of that type.
ArrayList implements Serializable so you can put the whole thing as it is by using...
MyIntent.putExtra("AnsweredBoolAR", Answered);
...then when you want to retrieve it from the Intent just use the getSerializableExtra(...) method of Intent.
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.
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.