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.
GetExternalFilesDir. Returns the absolute path to the directory on the primary external filesystem (that is somewhere on Android.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With