Kotlin - Why is this variable null after initialization? - android

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.

Related

Intent data is missing on onActivityResult()

I am creating an Intent and using putExtras I am adding an entity data which looks right but in onActivityResult(), some of the data is not received
Intent code:
Thanks
R
Update
When passing a Parcelable value through an Intent causes some of the information in that object to "disappear", the problem is almost always in the parceling/unparceling code of that class. Double-check to make sure that you're correctly saving and restoring all fields.
Update
In your posted code for SetFilterEntity, there is only one constructor: the one that takes a Parcel. Simply add the default constructor to this class:
public SetFilterEntity() {
// init values or just leave them default
}

When an object added to a Bundle can no longer be updated?

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.

BadParcelableException on passing TurnBasedMatch in intent

I'm developing a game with turn based multiplayer support. To fetch a list of the current games of a player I use the GamesClient.loadTurnBasedMatches method. This works fine but when I try to open a new activity and pass a match to it crashed. The code I use to launch the new activity is
private void openMatch(TurnBasedMatch match) {
Intent intent = new Intent(this, MultiPlayerGame.class);
intent.putExtra("match", match);
startActivity(intent);
}
But after executing this code I get this error: (It is limited like this so I can't see the entire package name)
02-03 21:28:02.880: E/AndroidRuntime(5513): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mypackage.MultiPlayerGame}: android.os.BadParcelableException: Parcelable protocol requires a Parcelable.Creator object called CREATOR on class com.google.android.gms.games.multiplayer.turnbased.a
The line where it actually crashes is:
match = getIntent().getExtras().getParcelable("match");
Now I'm not sure if this is a fault of mine or is there a bug somewhere in the play-services-lib. Or is it related to proguard? Btw, if I use the built in intent to show the user his games the same method works. (in onActivityResult)
if (request == RC_LOOK_AT_MATCHES) {
TurnBasedMatch match = data.getParcelableExtra(GamesClient.EXTRA_TURN_BASED_MATCH);
if (match != null)
openMatch(match);
}
Your TurnBasedMatch must implement Parcelable contract. See examples here or here
I managed to work around it by only sending the matchId to the next activity. In that activity I use GamesClient.getTurnBasedMatch. It might be that the default intent does this in the backgroud but I'm not sure.
Try
intent.putExtra("match", new TurnBasedMatchEntity(match));
TurnBasedMatchEntity is a class that implements TurnBasedMatch and supports being sent as a Parcelable. You can retrieve it the same way as before.
TurnBasedMatch match = getIntent().getExtras().getParcelable("match");
TurnBasedMatch (and all of its implementations) implement Freezable<>, which has a freeze() method. Calling it will get you an instance that's suitable for serialization.
I suspect (but haven't confirmed) that the call to freeze() simply returns a TurnBasedMatchEntity object. The nice thing about this solution is you don't have to care; all you have to care about is what's defined in the interface.
As a side note, the TurnBasedMatch interface extends Parcelable, which should mean every implementation is also parcelable... but it appears TurnBasedMatchRef doesn't actually implement it (hence the exception). Implementations shouldn't violate their interfaces like this, but that appears to be how it is.

LinkedList put into Intent extra gets recast to ArrayList when retrieving in next activity

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

putExtra() in android

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.

Categories

Resources