0

I have been trying iTextpdf today ang got into some shoddy error. mainly: java.io.FileNotFoundException: /storage/emulated/0/Download/pdfdemo20170521_145348.pdf: open failed: EACCES (Permission denied)

I have already implemented the proper permissions like

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

but it also does not work. here is the code for my file processing:

public class SelfNoteFragment extends Fragment {
private View mRootView;
private EditText mSubjectEditText, mBodyEditText;
private Button mSaveButton;

public SelfNoteFragment() {
    // Required empty public constructor
}

public static SelfNoteFragment newInstance(){
    SelfNoteFragment fragment = new SelfNoteFragment();
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    mRootView = inflater.inflate(R.layout.fragment_self_note, container, false);
    mSubjectEditText = (EditText) mRootView.findViewById(R.id.edit_text_subject);
    mBodyEditText = (EditText) mRootView.findViewById(R.id.edit_text_body);
    mSaveButton = (Button) mRootView.findViewById(R.id.button_save);

    mSaveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mSubjectEditText.getText().toString().isEmpty()){
                mSubjectEditText.setError("Subject is empty");
                mSubjectEditText.requestFocus();
                return;
            }

            if (mBodyEditText.getText().toString().isEmpty()){
                mBodyEditText.setError("Body is empty");
                mBodyEditText.requestFocus();
                return;
            }

            try {
                createPdf();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "FILE", Toast.LENGTH_SHORT).show();
            } catch (DocumentException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "Document", Toast.LENGTH_SHORT).show();
            }
        }
    });
    return mRootView;
}


private void createPdf() throws FileNotFoundException, DocumentException {

    File pdfFolder = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS), "pdfdemo");
    if (!pdfFolder.exists()) {
        pdfFolder.mkdir();
        Log.i("TAG", "Pdf Directory created");
    }

    //Create time stamp
    Date date = new Date() ;
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);

    //Filename
    File myFile = new File(pdfFolder + timeStamp + ".pdf");

    OutputStream output = new FileOutputStream(myFile);

    //Designate the size
    Rectangle pagesize = new Rectangle(216f, 720f);
    Document document = new Document(pagesize, 36f, 72f, 108f, 180f);

    PdfWriter.getInstance(document, output);

    //OPEN ITEXT FOR DOCUMENT SCANNING
    document.open();

    document.add(new Paragraph(mSubjectEditText.getText().toString()));
    document.add(new Paragraph(mBodyEditText.getText().toString()));

    //If scanning is done, Close the document
    document.close();

}

when i look at my logcat, an error on the line 107 appears. which is the line of: OutputStream output = new FileOutputStream(myFile);

JJCADIZ
  • 143
  • 2
  • 14
  • If on Android six and above requesting permissions in manifest is not enough. You should add code to ask the user to grant those permissions too. Runtime permissions. – greenapps May 21 '17 at 07:17
  • `pdfFolder.mkdir(); Log.i("TAG", "Pdf Directory created");`. Misleading log and untrue. Check the return value of mkdir. And handle acvordingly. Your directory is not created. And you do not know it. And you continue as if it was there. – greenapps May 21 '17 at 07:19
  • how do i prompt for them to ask permissions? all i did was include in manifest. – JJCADIZ May 21 '17 at 07:26
  • Well meanwhile you have googled for runtime permissions was the idea. You can also go to Settings of your app and switch them on manually with the toggle button. – greenapps May 21 '17 at 07:27

1 Answers1

2

For sdk>=23 you need to ask Runtime permission.

Here is a list of Runtime permission required in Android Os.

in your Oncreate()

Ask for Permission using:

if (Build.VERSION.SDK_INT >= 23) {
    if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED) {
       //you code..
       //read_file()
    } else {
        //request permission
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
    }
}
else { 

    //permission is automatically granted on sdk<23 upon installation
    //Your code
    //read_file()
}

Catch the permission result in:

    @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {

        case 0: {

            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
                //read_file()
            } else {
                Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
 }
Community
  • 1
  • 1
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62