Home > Enterprise >  val child: ImageView = gridLayout.getChildAt(i) as ImageView crashes my app
val child: ImageView = gridLayout.getChildAt(i) as ImageView crashes my app

Time:01-29

when i run my app it's crash in this phrase ( sorry for bad English )

i tried a lot to soloute to this problem but i cannt enter image description here

CodePudding user response:

gridLayout.getChildAt return null as the message says.

Try changing your condition with gridLayout.getchildCount()-1

CodePudding user response:

You are looping until the gridlayout childCount and array indices start at 0 in kotlin.

So if you have an array of 10 elements, to access the first element you index it like array[0], for the second element you use array[1] and so on. So if you try to access array[10] that means you are trying to get the 11th element which doesn't exist as your array has a total of 10 elements. The last element in this example array is at index 9 so you access it by calling array[9].

In your case by looping until gridLayout.getChildCount(), when the loop reaches the last element it will try to access an element that doesn't exist in the array. So you should loop until gridLayout.getChildCount() - 1 because that's the correct index for the last element.

  • Related