Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting list of images from a folder in android kotlin

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?

like image 285
evals Avatar asked Jul 04 '18 07:07

evals


2 Answers

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
like image 62
Jay Rathod RJ Avatar answered Oct 31 '22 13:10

Jay Rathod RJ


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!!
}
like image 29
Ankita Avatar answered Oct 31 '22 14:10

Ankita