1

I have written a code for java to Json, while retrieving a Sting value from a Page that is Latitude from a Page properties throwing an error : java.lang.ClassCastException. Here I am using ValueMap if it contains that latitude value then I have to store it in Double. The Code sample is

import org.apache.sling.api.resource.ValueMap
private static final String G_LAT = "37.7608337";
protected ValueMap pageProp;
Double lat = null;
if(pageProp.containsKey(G_LAT))

lat = (Double) pageProp.get(G_LAT); // Getting an exception here

Thank You for any help!

User
  • 35
  • 1
  • 3
  • To avoid bad cast, you can cast into `java.lang.Number` as `java.lang.Long` inherits from `java.lang.Number`. Then, use the method `doubleValue()` on the retrieved number. – cardman Feb 20 '17 at 16:18
  • 1
    Can you please provide some syntax – User Feb 20 '17 at 16:41
  • `Long longLat = (Long) pageProp.get(G_LAT);` `lat = longLat.doubleValue();` – cardman Feb 20 '17 at 16:45
  • 1
    after trying the above syntax compiler error and it's forcing me to Change type of lat to double – User Feb 20 '17 at 16:49
  • I think you have to remove the semi column after the if, you will have: `if(pageProp.containsKey(G_LAT)) {Long longLat = (Long) pageProp.get(G_LAT); lat = longLat.doubleValue();} ` – cardman Feb 20 '17 at 16:55
  • 1
    Still getting compiler error – User Feb 20 '17 at 17:02

2 Answers2

0

You can use Double.parseDouble() to convert a String variable to double.

String str="2.036"
Double d=Double.parseDouble(str);
rajat188
  • 86
  • 1
  • 9
0

This seems to a cast exception please refer the following url

java.lang.Long cannot be cast to java.lang.Double

you can try this instead. lat = (Double) pageProp.get(G_LAT,long);

The get method returns a Object which will be typecast to the Double which is a narrowing operation. Hence try to convert the object to long before casting that to a Double.

Community
  • 1
  • 1