-2

I have the following code:

File vcfFile = new File(this.getExternalFilesDir(null), "generated.vcf");
FileWriter fw = new FileWriter(vcfFile);
fw.write("BEGIN:VCARD\r\n");
...

It works fine on newer APIs, but on API 18 it crashes.

Caused by: java.io.FileNotFoundException: /generated.vcf: open failed: EROFS (Read-only file system)

I think this is the reason, but I can't find a work-around. It is the main feature of the app, so removing it isn't really an option for me.

2 Answers2

1

You need to hold the WRITE_EXTERNAL_STORAGE permission to write to getExternalFilesDir() on Android 4.3 and older. Only on Android 4.4+ can you skip it for that location.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

You need to have the permission to write to the external Storage. With the new API's you need to both declare the permission in the manifest and also ask for the permission during runtime.

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {

        // No explanation needed, we can request the permission.

        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

        // MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}

You can check this link for further details:https://developer.android.com/training/permissions/requesting.html

Pronoy999
  • 645
  • 6
  • 25