Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android says cannot resolve method 'getExternalFilesDir(null)'

I am using Android Studio to try to write a file to external storage.

Other posts have recommended I do this using getExternalFilesDir(null), but I get the message 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.

like image 736
Olivia Watkins Avatar asked Jan 06 '16 17:01

Olivia Watkins


People also ask

What is the use of GetExternalFilesDir () method in Android?

GetExternalFilesDir. Returns the absolute path to the directory on the primary external filesystem (that is somewhere on Android.

What is GetExternalFilesDir?

getExternalFilesDir() It returns the path to files folder inside Android/data/data/your_package/ on your SD card. It is used to store any required files for your app (e.g. images downloaded from web or cache files). Once the app is uninstalled, any data stored in this folder is gone too. getExternalStorageDirectory()


1 Answers

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.

Like:

  • getActivity().getExternalFilesDir(null) in Fragment

  • context.getExternalFilesDir(null) in classes, where you pass Context as parameter

  • YourActivity.this.getExternalFilesDir(null); when called in inner class of Activity

like image 58
Damian Kozlak Avatar answered Oct 17 '22 11:10

Damian Kozlak