简体   繁体   English

较旧的android版本上的android字符串数组nullpointerexception

[英]android string array nullpointerexception on older android versions

This code works fine on android 4.4, 5.0, 5.1 , 6.0 这段代码可以在android 4.4、5.0、5.1、6.0上正常工作

 File file = new File("/storage/emulated/0//Videos/");
    String[] myFiles;
    myFiles = file.list();
    for (int i = 0; i < myFiles.length; i++) {
        File myFile = new File(file, myFiles[i]);
        myFile.delete();
 }

But when i use this for android 4.0, 4.1, 4.2 i get java.lang.NullPointerException referring at line 但是当我将其用于android 4.0、4.1、4.2时,我得到java.lang.NullPointerException在行引用

for (int i = 0; i < myFiles.length; i++)

So i try to initialize the String, 所以我尝试初始化字符串,

String[] myFiles = new String[100] //just big value

But android studio shows initializer "new String[100]" is redundent and error is not resolved. 但是android studio显示初始化程序“ new String [100]”是多余的,错误无法解决。

Why does this happen? 为什么会这样?

Thanks..! 谢谢..!

The javadoc for File.list() says that it can return null. File.list()的Javadoc说它可以返回null。 You should always check for this whenever you call it and handle it correctly unless you are absolutely certain it will not return null. 除非绝对确定它不会返回null,否则无论何时调用它,都应始终对其进行检查并正确处理。

This is because you are not checking your folder is null or not make sure your directory contains file 这是因为您没有检查文件夹为空或不确定目录是否包含文件

File file = new File("/storage/emulated/0//Videos/");
String[] myFiles;
if (file == null) {

} else {
    myFiles = file.list();
    for (int i = 0; i < myFiles.length; i++) {
        File myFile = new File(file, myFiles[i]);
         if(myFile.exists())
        myFile.delete();
    }
}

And if you want to delete whole directory than you can use this sample method 如果要删除整个目录,则可以使用此示例方法

public void deleteDirectory(File file) {
if( file.exists() ) {
    if (file.isDirectory()) {
        File[] files = file.listFiles();
        for(int i=0; i<files.length; i++) {
            if(files[i].isDirectory()) {
                deleteDirectory(files[i]);
            }
            else {
                files[i].delete();
            }
        }
    }
        file.delete();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM