修复android中的警告NullPointerException
下面的代码在我运行Inspect代码时给出警告。如何更改它以修复警告修复android中的警告NullPointerException,android,Android,下面的代码在我运行Inspect代码时给出警告。如何更改它以修复警告 File contents = new File(context.getExternalFilesDir(null).getAbsolutePath(), "Contents"); if (!contents.exists()) { contents.mkdirs(); } 警告: 方法invocatiom“getAbsolutePath”可能会
File contents = new File(context.getExternalFilesDir(null).getAbsolutePath(), "Contents");
if (!contents.exists()) {
contents.mkdirs();
}
警告:
方法invocatiom“getAbsolutePath”可能会生成“NullPointerException”
并且文件
mkdirs()
被忽略您可以使用boolean
获得mkdirs()的结果
对于NullPointerException
,您可以使用
File contents = new File(Objects.requireNonNull(context.getExternalFilesDir(null)).getAbsolutePath(), "Contents");
//requireNonNull needs min API = 19
希望这会有帮助 从文档中:
共享存储可能并不总是可用的,因为用户可以弹出可移动媒体。可以使用环境#getExternalStorageState(文件)检查媒体状态
您需要先进行一些检查:
File externalDir = context.getExternalFilesDir(null);
if(externalDir == null) {
throw new IllegalStateException("No External files directory found.");
}
if(Environment.getExternalStorageState(externalDir).equals(Environment.MEDIA_MOUNTED)) {
throw new IllegalStateException("External Storage not mounted correctly.");
}
File contents = new File(externalDir.getAbsolutePath(), "Contents");
if (!contents.exists()) {
contents.mkdirs();
}
您可以用标志、日志或程序需要的任何内容替换异常
Objects.requirennoull仅显示空位置。是否正确?这不是必需的,请检查@Diego如果您发现这有帮助,请记住向上投票或将其标记为已回答
File externalDir = context.getExternalFilesDir(null);
if(externalDir == null) {
throw new IllegalStateException("No External files directory found.");
}
if(Environment.getExternalStorageState(externalDir).equals(Environment.MEDIA_MOUNTED)) {
throw new IllegalStateException("External Storage not mounted correctly.");
}
File contents = new File(externalDir.getAbsolutePath(), "Contents");
if (!contents.exists()) {
contents.mkdirs();
}