简体   繁体   English

Android说无法解析方法'getExternalFilesDir(null)'

[英]Android says cannot resolve method 'getExternalFilesDir(null)'

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. 预先感谢您对问题的任何解决方案。

getExternalFilesDir() is method which requires Context . getExternalFilesDir()是需要Context方法。 In Activity class you just need to call getExternalFilesDir() , but in other classes you need to call it with Context . 在Activity类中,您只需要调用getExternalFilesDir() ,但是在其他类中,您需要使用Context来调用它。

Like: 喜欢:

  • getActivity().getExternalFilesDir(null) in Fragment 片段中的getActivity().getExternalFilesDir(null)

  • context.getExternalFilesDir(null) in classes, where you pass Context as parameter context.getExternalFilesDir(null) ,您可以在其中传递Context作为参数

  • YourActivity.this.getExternalFilesDir(null); when called in inner class of Activity 在Activity的内部类中调用时

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM