Abdul Rahman Shamair
Abdul Rahman Shamair

Reputation: 578

MutableList not adding new values Kotlin

I am getting list of file's path from a specific folder, but when I try to add it in my mutable list, the list remains empty.

var filePath: MutableList<String>? = null
val path = File(getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).path, "BacFo Camera")
if (path.exists()) {
    for(i in path.list().iterator()){
        filePath?.add("" + path.toString() + "/" + i)  //here i=file name
    }
}

After running Debugger the values does come in variable i but some how the mutable list remain empty. I am new to Kotlin, Please help!!

Upvotes: 1

Views: 6287

Answers (3)

Simulant
Simulant

Reputation: 20142

You declared your MutableList but initialized it with null. So the variable is reserved but is not initialized with a list.

When you try to add a value to the List, you use a safe call ?. that is only executed, when the value (your list) is not null. But actually it is null to the call is not executed.

You should initialize your List e.g. with an ArrayList.

var filePath: MutableList<String>? = ArrayList<String>()

As you always initialize your List now, you can even use the val instead of var and can get rid of the save call:

val filePath: MutableList<String>? = ArrayList<String>()
val path = File(getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).path, "BacFo Camera")
if (path.exists()) {
    for(i in path.list().iterator()){
        filePath.add("" + path.toString() + "/" + i)  //here i=file name
    }
}

Upvotes: 3

Try this:

var filePath: MutableList<String> = arrayListOf()

Upvotes: 2

CommonsWare
CommonsWare

Reputation: 1007554

the list remains empty.

No, the list is null:

var filePath :MutableList<String> ?=null

Try assigning it a value:

var filePath: MutableList<String> = mutableListOf()

Upvotes: 12

Related Questions