android - 从android kotlin中的文件夹获取图像列表

标签 android arraylist nullpointerexception kotlin indexoutofboundsexception

我正在尝试使用此函数从文件夹中获取图像列表

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!!
}

但我有这些异常(exception):

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

kotin.kotlinNullPointerException

我读到过这个问题,但我不知道如何解决,

有什么帮助吗?

最佳答案

对于空指针,您可能需要在 var list = imageReader(path)< 中更改并传递 fullpath 而不是 path/.

错误

var fullpath = File(gpath + File.separator + spath)
var list = imageReader(path)

var gpath:String = Environment.getExternalStorageDirectory().absolutePath
var spath = "testfolder"
var fullpath = File(gpath + File.separator + spath)
var list = imageReader(fullpath)

编辑 1

我对函数做了一些更改并将其应用到 override fun onCreate 中,如下所示。

var gpath: String = Environment.getExternalStorageDirectory().absolutePath
var spath = "Download"
var fullpath = File(gpath + File.separator + spath)
Log.w("fullpath", "" + fullpath)
imageReaderNew(fullpath)

函数

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 输出

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

关于android - 从android kotlin中的文件夹获取图像列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51168486/

相关文章:

Java数组将输入保存到txt文件

java - 添加keylistener返回空指针异常

java - 如何检查参数是否为空

android - 文件仅在重启 Android 设备后写入

android - 使用循环设置按钮 onclicklistener

android 加载多个标记 block 我的 UI

java - Kotlin 中可调整大小的二维数组

java - 尝试在 ArrayList 中 6 个按钮中的 1 个按钮上绘制半透明正方形时出现奇怪的结果

java - 在不同包的子类中使用 super() 作为 equals()

android - CircleCI 可以为 Android 项目做单元/浓缩咖啡测试吗?