I'm new to Android/Java. I'd like to write a test application where any arbitrary extra that I add to a (custom) intent is printed.
When I receive the intent with my BroadcastReceiver
, I can get all the extras as Bundle and their keys by:
Bundle bundle = intent.getExtras();
Set<String> keys = bundle.keySet();
How do I find out what is the type of a value associated with a given key?
What I was thinking is something like:
Object tmp = bundle.get(key);
// utilize https://stackoverflow.com/questions/709961/
But this way doesn't seem to be the best idea. Another option seems to be something like:
if (bundle.getBoolean(key) == null) {
// can't determine if `null` was explicitly associated or not
} else if /* ... */
but this way I cannot determine if the null value was intended or not. I could create a custom default value class, but I'm not sure this is the intended way. edit I've just realized I need a default value of the same type, so I can't even do this. (One could double-check for null and a custom default typed value to know, though.)
How do I know the type of a value for a given key dynamically?
Maybe I should explain me better through an answer better than a comment.
You can do what you want doing this.
Object tmp = bundle.get(key);
if (tmp instanceof Boolean) {
boolean finalValue = ((Boolean)tmp).booleanValue();
}
If you check the source from Android you will see something similar, they always pass the wrapper not the primitive type.
public boolean More ...getBoolean(String key, boolean defaultValue) {
Object o = mMap.get(key);
if (o == null) {
return defaultValue;
}
try {
return (Boolean) o;
} catch (ClassCastException e) {
typeWarning(key, o, "Boolean", defaultValue, e);
return defaultValue;
}
}
The difference is that they do not check the type of the object as they suppose you know what you are doing.