我正在尝试使用此功能从文件夹中获取图像列表
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!!
}
但是我有这些例外:
java.lang.ArrayIndexOutOfBoundsException:length = 3; index = 3
kotin.kotlinNullPointerException
我已经读过这个问题,但是我不知道如何解决,
有什么帮助吗?
答案 0 :(得分:1)
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!!
}
答案 1 :(得分:1)
对于空指针,您可能需要更改并传递 fullpath 而不是var list = imageReader(path)
内的 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
我对功能进行了很少的更改,并将其应用于 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
答案 2 :(得分:0)
上面的答案是正确的,但是它将a
声明为null
,然后在循环中使用null
保存。因此,它会检测图像,但不会将其添加到列表中,并且列表返回null。
fun imageReader(root: File): ArrayList < File > {
val a: ArrayList < File > = ArrayList()
if (root.exists()) {
val files = root.listFiles()
if (files.isNotEmpty()) {
for (i in 0..files.size - 1) {
if (files[i].name.endsWith(".jpg")) {
a.add(files[i])
}
}
}
}
return a!!
}