0

This is how I'm trying to do it:

public void SaveImageToMemory(Bitmap bitmap, String fileName){
    File outFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ImageEncryptionDemo", fileName+".jpeg");
    try {
        outFile.getParentFile().mkdirs();
        outFile.createNewFile();
        FileOutputStream outStream = new FileOutputStream(outFile);

        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        outStream.flush();
        outStream.close();

        Log.i("app", "Saved image to " + outFile.getAbsolutePath());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (java.io.IOException e){
        e.printStackTrace();
    }
}

I've no idea why it throws IOException even if:

  1. Permissions in Android Manifest are granted
  2. outFile.getParentFile().mkdirs(); should ensure that all necessary parent directories are created
  3. Below functions (taken from android docs) return true

:

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
            Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

Permissions in AndroidManifest:

<manifest [...]>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
Piotrek
  • 10,919
  • 18
  • 73
  • 136
  • 1
    https://stackoverflow.com/questions/32635704/android-permission-doesnt-work-even-if-i-have-declared-it – CommonsWare Feb 17 '18 at 16:11
  • What's the value of `Environment.getExternalStorageDirectory().getAbsolutePath()`? What is the result of `mkdirs` (it returns `true` or `false` if the operation succeeded or failed)? Where exactly is the exception thrown and what is the complete stacktrace? Oh, and what is the value of `fileName`? – Lothar Feb 17 '18 at 16:16
  • @CommonsWare that was actually a problem. I needed to ask for permissions. Thanks. – Piotrek Feb 17 '18 at 17:16

1 Answers1

0

In 2nd line, you had just got confused. Check this out.

    File outFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/ImageEncryptionDemo/" + fileName+".jpeg");

After

    /ImageEncryption/

You have to use + instead of a comma.

Dipanshu Mahla
  • 152
  • 1
  • 16