Android getExternalFilesDir(null)为某些用户返回null
所以我的问题是 下面这行代码为我的应用程序的一些用户抛出了一个NullPointerException,但我不知道为什么Android getExternalFilesDir(null)为某些用户返回null,android,nullpointerexception,Android,Nullpointerexception,所以我的问题是 下面这行代码为我的应用程序的一些用户抛出了一个NullPointerException,但我不知道为什么 String state = Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(state)) baseDir = getExternalFilesDir(null).getAbsolutePath(); else baseDir = getFilesDir()
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state))
baseDir = getExternalFilesDir(null).getAbsolutePath();
else
baseDir = getFilesDir().getAbsolutePath();
更具体地说,是这一部分
baseDir = getExternalFilesDir(null).getAbsolutePath();
这段代码是在onpostreate()中调用的,如果您不知道的话,我也拥有所需的权限
因此,getExternalFilesDir(null)出于某种原因返回null,即使它将被装载
我也搜索了一下,找到了相关的帖子,上面有同样的问题,但没有真正的答案,只有一个好的答案
那么这仅仅是一些用户手机上的问题还是androids end上的一般问题?这很奇怪。android文档说,它只在外部存储未装入时返回null。我认为正确的做法是:
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)) {
File baseDirFile = getExternalFilesDir(null);
if(baseDirFile == null) {
baseDir = getFilesDir().getAbsolutePath();
} else {
baseDir = baseDirFile.getAbsolutePath();
}
} else {
baseDir = getFilesDir().getAbsolutePath();
}
嗯,是的,我想这几乎是唯一的解决办法。然而,了解为什么会发生这种情况是很有趣的。我唯一的假设是它取决于制造的实现。我也看到过这个问题,但对我来说,它是零星的,不依赖于用户。我认为这是操作系统中的一个时间问题,但我还没能做到,所以我不能提交错误报告。