gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 09:25:19 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com