java Android 表示无法解析方法“getExternalFilesDir(null)”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34638931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android says cannot resolve method 'getExternalFilesDir(null)'
提问by Olivia Watkins
I am using Android Studio to try to write a file to external storage.
我正在使用 Android Studio 尝试将文件写入外部存储。
Other posts have recommended I do this using getExternalFilesDir(null)
, but I get the message Cannot resolve method 'getExternalFilesDir(null)'
.
其他帖子建议我使用此方法getExternalFilesDir(null)
,但我收到了消息Cannot resolve method 'getExternalFilesDir(null)'
。
public void makeFile() {
try {
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
File file = new File(getExternalFilesDir(null), "outputFile.txt");
FileOutputStream fos = new FileOutputStream(file);
String text = "Hello, world!";
fos.write(text.getBytes());
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I haven't been able to find any way to get rid of this error. Thanks in advance for any solutions to the problem.
我一直无法找到任何方法来摆脱这个错误。在此先感谢您对问题的任何解决方案。
回答by Damian Kozlak
getExternalFilesDir()
is method which requires Context
. In Activity class you just need to call getExternalFilesDir()
, but in other classes you need to call it with Context
.
getExternalFilesDir()
是需要Context
. 在 Activity 类中,您只需要调用getExternalFilesDir()
,但在其他类中,您需要使用Context
.
Like:
喜欢:
getActivity().getExternalFilesDir(null)
in Fragmentcontext.getExternalFilesDir(null)
in classes, where you passContext
as parameterYourActivity.this.getExternalFilesDir(null);
when called in inner class of Activity
getActivity().getExternalFilesDir(null)
在片段中context.getExternalFilesDir(null)
在类中,您在其中Context
作为参数传递YourActivity.this.getExternalFilesDir(null);
在 Activity 的内部类中调用时