I recently ran into some issues with android.os.Bundle
that I hoped to fix by simply extending the class and making it more loosely-typed. The specific problem that I ran into was errors like:
W/Bundle ( 6782): Key access_token expected byte[] but value was a java.lang.String. The default value <null> was returned.
W/Bundle ( 6782): Attempt to cast generated internal exception:
W/Bundle ( 6782): java.lang.ClassCastException: java.lang.String
W/Bundle ( 6782): at android.os.Bundle.getByteArray(Bundle.java:1305)
Of course, conversion from String
to byte[]
is trivial, so my thought was to just have the Bundle
do this conversion automatically if it's looking for a byte[]
but finds a String
instead. It's silly that it doesn't do this already (and also that it has specific getters and setters for pretty much every primitive type and a few different Object
types instead of generic ones that just work in terms of Object
, or at worst Number
, String
, and Parcelable
), in my opinion.
But anyways, I quickly discovered that I can't fix the problem by extending Bundle
, because it is declared final
. Is there any known/specific reason for this? There are other classes in android.os
that are not final
, so what makes Bundle
worthy of this assignation?
Also, any ideas on how to work around this? A wrapper class is out as there is no common interface
for it to implement (the code that actually causes the issue is part of a third-party library, so I can't just update it to refer directly to a wrapper class).
I guess that leaves the only option hunting down all the places in the code that happen to be setting up String
values for things that the third-party code expects to be passed as byte arrays.
Basically all "primitive" types are final. There are a couple reasons for this. First the bundle is meant to be parceable and you might break some if its semantics by overwriting. Also , Bundle is meant to always act a certain way. If you overwrote it you could change the behavior people are expecting or even throw an exception breaking code that was considered safe before. It could also probably be argued that it would be a security vulnerability to allow it since they could overwrite it with code that could track what happened to it.
The class is final because you shouldn't NEED to inherit it. The documentation shows that there's a ton of methods for get
ing and put
ing all kinds of types. If you are really concerned about converting a String
to a byte[]
, then what you're looking for is a Java method (click me), and not something unique to Android.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With