我需要一个Android应用程序目录路径来将我的应用程序图片与所有版本兼容。我搜索了很多,我还没有找到与所有设备兼容的东西。现在我们有这段代码,但它仍然在picturesDir.exists()
与U55
和ZTE
设备提供NullPointerExcepction。创建与所有版本和设备兼容的Android应用程序目录
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();
}
我们应该做什么?我不想检查它是否为空以避免崩溃。我想要一个可以保存图片的路径。谢谢。
“它仍在给NullPointerExcepction” - 请编辑您的问题并发布与此异常相关的完整Java堆栈跟踪。我相信你的算法和设备一样是你难度的来源,堆栈跟踪将帮助我确认你的症状。 – CommonsWare
即使您在检查SD卡状态过程中以某种方式避免错误,也可能随时提取SD卡或发生IO错误。所以你必须捕捉IO错误。不要试图不惜代价使代码变得漂亮,你不能这样做。 – user1643723
刚编辑的CommonsWare! –