I am quite confused with the concept of External Storage. I have a following code underneath where I wanted to save my bitmap drawing into the Internal Storage.
FileOutputStream outStream = null;
File filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File dir = new File(filePath.getAbsolutePath(), "/Test_Folder");
if (dir == null || !dir.mkdirs()) {
Log.e("File", "Directory not created");
Toast.makeText(getActivity(), "Directory not created", Toast.LENGTH_SHORT).show();
}
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(getActivity(), "Saved to Gallery", Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
So in my Samsung Android, it saves into the "Internal Memory". For the Android Studio emulator, it saves into the "SD Card", and for some other devices, it would either Log or Toast "Directory not created".
I have read some very old posts about storage/emulated/0 is the chosen "default storage"? How do I target to a very specific storage type and why is it that sometimes other devices do not write?
EDIT: Okay so I have now understood that as an Android User, the thing we perceive as "Internal Storage/Memory" is still technically "External Storage" (Thanks for making this clear! Do please correct me if I'm wrong)
So turns out this is our Android versions accordingly:
- Samsung : Android 13
- Emulator : Android 11
- 'Other Devices' : Android 9 and Android 10
It asked the Will you allow this app to access files? Prompt with Allow or Deny options for Androids 11, 9, and 10.
It can only save in Androids 13 (No Prompt) , and 11 (With Prompt).
Included this to check for versions:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
{
dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + FolderName);
Log.e("File", ">=R File:" + dir);
}
else
{
dir = new File(Environment.getExternalStorageDirectory() + "/" + FolderName);
Log.e("MountedMedia", Environment.getExternalStorageDirectory().toString());
Log.e("File", "<R File:" + dir);
}
// Make sure the path directory exists.
if (!dir.exists())
{
// Make it, if it doesn't exit
boolean success = dir.mkdirs();
if (!success)
{
dir = null;
Log.e("File", "Directory not created");
}
}
But for the 'Other Devices', it would always Log Directory not Created even if I confirmed in the settings that Storage Permissions is allowed. Not sure if I miss something this time