Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Bundle, how do I find out the type of a value for a given key?

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?

like image 421
n611x007 Avatar asked Oct 22 '13 13:10

n611x007


2 Answers

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.

source

like image 130
Juangcg Avatar answered Sep 21 '22 08:09

Juangcg


I believe you cant determine the type, if you send the intent then you know what to receive, if you are receiving intent from other application just read their documentation. They would document it if they want you to use it :)

like image 25
Ahmad Dwaik 'Warlock' Avatar answered Sep 22 '22 08:09

Ahmad Dwaik 'Warlock'