Home > Software design >  painterResource for null IDs
painterResource for null IDs

Time:10-02

I have a list of images and a variable with can be anything from -1 to 13.
But the list contains only 3 indexes, so I have set a condition.

items[if(myInt == null) R.drawable.placholder else myInt

But it crashes my app with this error,

java.lang.ArrayIndexOutOfBoundsException: length=4; index=4

My Code

val items = listOf(R.drawable.red, R.drawable.green, R.drawable.blue)
Image(painter = painterResource(items[if(myInt==null) R.drawable.placholder else myInt]), contentDescription = null)

CodePudding user response:

The shortest solution is using kotlin getOrElse. You can specify -1 instead of null:

items.getOrElse(myInt ?: -1) { failedIndex -> R.drawable.ic_undo }

A more detailed solution is to check if item.indices contains your index:

if (myInt != null && items.indices.contains(myInt)) {
    items[myInt]
} else {
    R.drawable.ic_undo
}

CodePudding user response:

From the Kotlin documentation, the correct way to access items in a list is by one of the methods below:

val list = listOf('a', 'b', 'c')
println(list.size) // 3
println("list.contains('a') is ${list.contains('a')}") // true
println(list.indexOf('b')) // 1
println(list[2]) // c

So, if your myInt var is anything but 0, 1, 2, or null and R.drawable.placholder returns anything but 0, 1, or 2, you will get an index out of bounds exception.

You might try something like this:

val items = listOf(R.drawable.red, R.drawable.green, R.drawable.blue)

var item = 0
if(myInt != null && items.contains(myInt)){
    item = myInt
}else{
    item = R.drawable.placholder
}

Image(painter = painterResource(item),contentDescription = null)
  • Related