2017-08-07 135 views
-1

我需要一个Android应用程序目录路径来将我的应用程序图片与所有版本兼容。我搜索了很多,我还没有找到与所有设备兼容的东西。现在我们有这段代码,但它仍然在picturesDir.exists()U55ZTE设备提供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(); 
    } 

enter image description here

我们应该做什么?我不想检查它是否为空以避免崩溃。我想要一个可以保存图片的路径。谢谢。

+0

“它仍在给NullPointerExcepction” - 请编辑您的问题并发布与此异常相关的完整Java堆栈跟踪。我相信你的算法和设备一样是你难度的来源,堆栈跟踪将帮助我确认你的症状。 – CommonsWare

+0

即使您在检查SD卡状态过程中以某种方式避免错误,也可能随时提取SD卡或发生IO错误。所以你必须捕捉IO错误。不要试图不惜代价使代码变得漂亮,你不能这样做。 – user1643723

+0

刚编辑的CommonsWare! –

回答

1

getExternalFilesDir的每个文档:“特定于应用程序的目录的绝对路径。如果共享存储当前不可用,可能会返回null”。因此,根据文件,如果您使用getExternalFilesDir,您检查为空。

除了未安装外,还有其他一些原因可能导致外部存储器不可用。拨打getExternalStorageState与致电getExternalFilesDir之间也有可能发生竞争。换句话说,在调用getExternalStorageState()将其报告为挂载状态之后,但在调用getExternalFilesDir之前,可能会立即卸载SD卡。这种竞争条件可能会导致您的崩溃。

+0

谢谢!我会检查一下,如果有些用户仍然给出这个错误,我会回到这里。谢谢。 –

相关问题