I'm trying to get list of images from a folder using this function
var gpath:String = Environment.getExternalStorageDirectory().absolutePath
var spath = "testfolder"
var fullpath = File(gpath + File.separator + spath)
var list = imageReader(fullpath)
fun imageReader(root : File):ArrayList<File>{
    val a : ArrayList<File> ? = null
    val files = root.listFiles()
    for (i in 0..files.size){
        if (files[i].name.endsWith(".jpg")){
            a?.add(files[i])
        }
    }
    return a!!
}
but i have these exceptions :
java.lang.ArrayIndexOutOfBoundsException:length=3;index=3
kotin.kotlinNullPointerException
I've read about this problem but i have no idea how to fix it,
any help please?
For Null Pointer you may need to change and pass fullpath instead of path inside var list = imageReader(path).
Wrong
var fullpath = File(gpath + File.separator + spath)
var list = imageReader(path)
Right
var gpath:String = Environment.getExternalStorageDirectory().absolutePath
var spath = "testfolder"
var fullpath = File(gpath + File.separator + spath)
var list = imageReader(fullpath)
EDIT 1
I have made few changes to function and apply it inside override fun onCreate as below.
var gpath: String = Environment.getExternalStorageDirectory().absolutePath
var spath = "Download"
var fullpath = File(gpath + File.separator + spath)
Log.w("fullpath", "" + fullpath)
imageReaderNew(fullpath)
Function
fun imageReaderNew(root: File) {
    val fileList: ArrayList<File> = ArrayList()
    val listAllFiles = root.listFiles()
    if (listAllFiles != null && listAllFiles.size > 0) {
        for (currentFile in listAllFiles) {
            if (currentFile.name.endsWith(".jpeg")) {
                // File absolute path
                Log.e("downloadFilePath", currentFile.getAbsolutePath())
                // File Name
                Log.e("downloadFileName", currentFile.getName())
                fileList.add(currentFile.absoluteFile)
            }
        }
        Log.w("fileList", "" + fileList.size)
    }
}
Logcat Output
W/fullpath: /storage/emulated/0/Download
E/downloadFilePath: /storage/emulated/0/Download/download.jpeg
E/downloadFileName: download.jpeg
E/downloadFilePath: /storage/emulated/0/Download/images.jpeg
E/downloadFileName: images.jpeg
E/downloadFilePath: /storage/emulated/0/Download/images (1).jpeg
E/downloadFileName: images (1).jpeg
                        fun imageReader(root : File):ArrayList<File>{
    val a : ArrayList<File> ? = null
    val files = root.listFiles()
    for (i in 0..files.size-1){
        if (files[i].name.endsWith(".jpg")){
            a?.add(files[i])
        }
    }
    return a!!
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With