1

I want to write a file to external storage in android but get the FileNotFoundException. I have put the permission

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

in my manifest and if I do a check like

Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)

it returns true. I have tried different solutions from questions from SO (Android saving file to external storage; Write a file in external storage in Android; Writing to external storage filenotfoundexception) but none seemed to work for me. Sorry for posting a duplicate question but Ive been searching for days and couldnt find an answer.

My Code is the following:

private void Writing(String erg) {

        TextView one = (TextView) findViewById(R.id.e1);

        File root = android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);

        File dir = new File (root.getAbsolutePath());
        dir.mkdirs();
        File file = new File(dir, "Test.txt");

        try {
            FileOutputStream f = new FileOutputStream(file);
            PrintWriter pw = new PrintWriter(f);
            pw.println(erg);
            pw.flush();
            pw.close();
            f.close();
            one.setText("File created");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            one.setText("Error1");
        } catch (IOException e) {
            e.printStackTrace();
            one.setText("Error2");
        }

    }

The Textview one ends up with printing Error1.

I'll appreciate any help.

Community
  • 1
  • 1
n.mueller
  • 11
  • 4
  • 1
    https://stackoverflow.com/questions/32635704/android-permission-doesnt-work-even-if-i-have-declared-it – CommonsWare Aug 25 '16 at 13:36
  • 1
    As CW pointed out. Android has moved to a more iOS-like permission management. Check out this project https://github.com/googlesamples/easypermissions for easier permission request and user response handling. – nstosic Aug 25 '16 at 13:39
  • Thank you guys so much! I was pulling my hair out! – n.mueller Aug 25 '16 at 13:50
  • 1
    I don´t know why some poeple want to use libraries for runtime permissions. There is not very much work to do to deal with them....you just need to follow the API: https://developer.android.com/training/permissions/requesting.html – Opiatefuchs Aug 25 '16 at 13:50
  • A call to `checkSelfPermission()` is supposedly only required on SDK >= 23, but get this error even with `WRITE_EXTERNAL_STORAGE` in my manifest building to SDK 21. My app works on Android 4.4.2 but not on 7.0. – Joe Lapp Apr 10 '18 at 02:41
  • Found my problem. Contrary to the docs, permission isn't automatically granted on Android 7.0 to pre SDK 23 apps, but you can go into the app manager to explicitly allow the requested permission. – Joe Lapp Apr 10 '18 at 03:57

0 Answers0