【发布时间】:2017-08-07 09:22:00
【问题描述】:
我需要一个与所有版本兼容的应用程序图片的 Android 应用程序目录路径。我已经搜索了很多,但我还没有找到任何与所有设备兼容的东西。现在我们有了这段代码,但它仍然在picturesDir.exists() 和U55 和ZTE 设备上给出NullPointerExcepction。
File picturesDir;
String state = Environment.getExternalStorageState();
// Make sure it's available, if there is no SD card, create new directory objects to make
// directory on device.
if (!Environment.MEDIA_MOUNTED.equals(state)) {
picturesDir = new File(Environment.getDataDirectory() + "/data/" + getApplicationContext().getPackageName() + "/Pictures/");
} else if (Environment.getExternalStorageState() != null) {
picturesDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
} else{
String externalStoragePath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
picturesDir = new File(externalStoragePath + getApplicationContext().getPackageName() + "/Pictures/");
}
if (!picturesDir.exists()) {
picturesDir.mkdir();
}
我们应该怎么做?我不想检查它是否为 null 以避免崩溃。我想要一个可以保存图片的路径。谢谢。
【问题讨论】:
-
“它仍然给出 NullPointerExcepction”——请编辑您的问题并发布与此异常相关的完整 Java 堆栈跟踪。我相信你的算法和设备一样是你的困难的根源,堆栈跟踪将帮助我确认你的症状。
-
即使您在检查 SD 卡状态时以某种方式避免了错误,也有可能随时提取 SD 卡或发生 IO 错误。所以无论如何你都必须捕获 IO 错误。不要不惜一切代价让代码变得漂亮,你做不到。
-
刚刚编辑过 CommonsWare!
标签: android directory android-external-storage android-storage