James
James

Reputation: 67

Android - Avoid saving to storage/emulated/0

I'm trying to save an image on the public storage directory using the below code. However, when this is saving to storage/emulated/0 and not to the public Pictures folder. I have used basically this exact code in another app and it's worked fine. Does anyone know why .getExternalStoragePublic directory is not returning the accessible /Pictures/ and instead returning storage/emulated/0 ?

I have "uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" in my Manifest file

File backupFile;
File appFolder;
String path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/CustomFolder";
appFolder = new File(path);
if (!appFolder.exists())
    appFolder.mkdir();
String fileName = "picture.jpg"
backupFile = new File(appFolder, fileName);
FileOutputStream output = null;
try {
    output = new FileOutputStream(backupFile);
    output.write(bytes);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    mImage.close();
    if (null != output) {
        try {
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 0

Views: 3869

Answers (1)

James
James

Reputation: 67

Nevermind, I figured it out. It turns out just having "uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" in the Manifest file is insufficient, and I had to put the following code before it to make it work:

    int CAMERA_PERMISSION_REQUEST_CODE = 2;
    int result = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (result != PackageManager.PERMISSION_GRANTED){
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            Toast.makeText(getActivity().getApplicationContext(), "External Storage permission needed. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},CAMERA_PERMISSION_REQUEST_CODE);
        }
    }

Upvotes: 1

Related Questions