1

I have done with code in Android:

List<String> spinnerArray =  new ArrayList<String>();
for (int i = 0; i < items.size(); i++) {
    LinkedTreeMap<String, String> item = (LinkedTreeMap) items.get(i);

    // THIS LINE THROW EXCEPTION
    double d = Double.parseDouble(item.get("id").toString());

    locations.put(Integer.parseInt(item.get("id")), item.get("name"));
    spinnerArray.add(item.get("name"));
}

I get the error when I define the "d" variable.
The strange thing is if I run the same line in the debug I get the double value I need.

UPDATE ANSWER

On the debug window I have:

items.get(i) = {LinkedTreeMap@5317} size = 5
0 = {LinkedTreeMap$Node@5378} "id" -> "1.0"
    key = "id"
    value = {Double@5384} "1.0"
9
  • Correct me if I'm wrong but, item.get("id") will return you a String so why use .toString() ? Commented Mar 13, 2018 at 12:04
  • You don't need toString(). Also, is it a double or an integer? You're parsing the ID twice Commented Mar 13, 2018 at 12:04
  • 1
    To try everything :( I already tried without .ToString() and I get the error, so I tried with .ToString() Commented Mar 13, 2018 at 12:05
  • Please add the stacktrace to the question Commented Mar 13, 2018 at 12:05
  • The only casting is happening at (LinkedTreeMap) items.get(i) . What does items contain? Commented Mar 13, 2018 at 12:05

2 Answers 2

2

Seems that LinkedTreeMap items is of type [String, Object] and not [String, String].

So your code should look like:

LinkedTreeMap<String, Object> item = (LinkedTreeMap) items.get(i);

Thanks to Timothy Truckle.

Sign up to request clarification or add additional context in comments.

1 Comment

Close, but the OP missuses the map as a "custom Object type" so that different keys have different value types. Therefore item must be LinkedTreeMap<String, Object>
1

The long term solution to your problem is to define a custom class to be used as Data Transfer Object (DTO) where you cann access an items properties in a typesafe way:

class Item {
   private double id;
   private String name;
   public void setId(double id){this.id=id;}
   public double getId(){ return id;}
   public void setName(String name){this.name = name;}
   public String getName(){return name;}
}

usage:

for (int i = 0; i < items.size(); i++) {
    Item item = (LinkedTreeMap) items.get(i);

    // THIS LINE THROW EXCEPTION
    double d = item.getId();

    locations.put((int)item.getId(), item.getName());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.