0

I am trying to write on the pdf file after creating it through intent but I am getting a permission denied error.

open failed: EACCES (Permission denied)

the intent i am using to create the file

  Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("application/pdf");
        intent.putExtra(Intent.EXTRA_TITLE,userInputFileName);
        ActivityForresults.launch(intent);

the code inside the ActivityForresults

   Intent data = result.getData();
                        String path = data.getData().getPath();
                        File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());

                        File file = new File(root, userInputFileName);

                        try {
                            FileOutputStream fileOutputStream = new FileOutputStream(file); 
                            pdfDocument.writeTo(fileOutputStream);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

I have added install time permission

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

I have also added run time permission

  String[] galleryPermissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.MANAGE_DOCUMENTS};
        if (EasyPermissions.hasPermissions(getActivity(), galleryPermissions)) {
            Log.i("local-dev", "permissions are granted");
        } else {
            EasyPermissions.requestPermissions(this, "Access for storage",
                    101, galleryPermissions);
        }
Amelia
  • 15
  • 3
  • 1
    A `Uri` is not a file. Use `ContentResolver` and `openOutputStream()` to get an `OutputStream` on the content location identified by the `Uri`. You can then write your content there, rather than trying to use `FileOutputStream`. – CommonsWare Feb 20 '22 at 17:37
  • @CommonsWare can you pls explain with example – Amelia Feb 21 '22 at 14:26
  • Here is [an entire free book on Android app development](https://commonsware.com/Jetpack/). Using the Storage Access Framework, is covered in [this chapter](https://commonsware.com/Jetpack/pages/chap-content-001.html). Using `ACTION_CREATE_DOCUMENT` specifically is covered in [this chapter](https://commonsware.com/Jetpack/pages/chap-files-004). Those chapters include both [Java](https://gitlab.com/commonsguy/cw-jetpack-java) and [Kotlin](https://gitlab.com/commonsguy/cw-jetpack-kotlin) samples. – CommonsWare Feb 21 '22 at 14:53

0 Answers0