Android problem with class connected to response from API

Viewed 23

i messed up with some api. For example im getting the response like:

"items": [
        {
          "metalSymbol": "ABC",
          "weightOverall": 4.529,
          "weightPerKilo": 3.6
        },
        {
          "metalSymbol": "CBA",
          "weightOverall": 0,
          "weightPerKilo": 0
        },
        {
          "metalSymbol": "BCA",
          "weightOverall": 0.354,
          "weightPerKilo": 0.28
        }
      ]

as you can see sometime the weightOverall and weightPerKilo is just a 0. My problem is that, i have the class file responds to this response but with Double variables. And always when i hit the item with 0 in some place im getting weird error.

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

This problem is weird because of fact, that the "items" was not null. It just having size like 3. So im getting this error when im trying to get the value like that:

List<Items> itemsList = getResults().get(i).getComponents();    
itemsList.getItems().get(1).getWeightOverall()

for example... Do someone know why im getting error like this?

2 Answers

As the error says, when the list's size is 1, .get(1) would give an exception, try to replace it with .get(0) and see if that fixes the error. Also, you need to check the size of the list before playing with indexes.

Here lies the problem,

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

The size of the list is 1, and you are trying to access the element at index 1, which is ofcourse not present. So its throwing an exception.

A solution would be to check for the size of the list. If the size is different from the expected size, then there must be something wrong with the network call.

Related