Casting error, String to Number

nano7 years ago

I am surprised to see that following piece of code
Extensible.java:

    public double getDouble(String key) {
        if (attributes.containsKey(key)) {
            return ((Number) attributes.get(key)).doubleValue();
        } else {
            return 0.0;
        }
    }

Why are you doing this way? String and Number class aren't consisted to cast each other. Just a moment ago, i tried to get a trip report, but the error was saying can't cast java.lang.string to java.lang.number,
It would be strange if you haven't seen this? or am I doing something wrong?

-Tnx

nejck7 years ago

That piece of code does not cast String to Number.

It casts Object that is found in attributes Map under the key (that is of type String).

There is nothing wrong with the code provided, but it's true, that the Object in attributes is not always a Number, so you have to be careful when to use which function (there are others too, like getBoolean, ...).

nano7 years ago

how do I get around this issue? I haven't changed anything on the source code. Just tried to get report trips.

tnx

nejck7 years ago

To answer your question you'll have to provide more data (exact version of server, copy of logs at the time of error - both wrapper and tracker-server.log if possible, device type, ...) :)

Anton Tananaev7 years ago

@nano, what version are you using? Did you upgrade from some older version? Are you trying to get report for the data that has been saved by old version?

nano7 years ago

Hello Anton,
I was using v3.10 and I didn't come from any older version, it was just a first one. I changed the code as following, not sure if it is the right solution you would do.

    public double getDouble(String key) {
        if (attributes.containsKey(key)) {
            /*return ((Number) attributes.get(key)).doubleValue();*/
            Object obj = attributes.get(key);
            if (obj instanceof Number) {
                return ((Number) obj).doubleValue();
            } else if (obj instanceof String) {
                return Double.parseDouble((String) obj);
            } else {
                return 0.0;
            }
        } else {
            return 0.0;
        }
    }
Anton Tananaev7 years ago

Looks fine, but I'm not sure why it's not a number.