This code works fine on 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
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.
Why does this happen?
Thanks..!
The javadoc for File.list() says that it can return 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.
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.