1

I'm using API 29 (Android 10) on a Samsung device for testing.
I want to create a simple txt file. This method is executed when clicking a button.

private void createFile() {
    String path = getExternalFilesDir(null).toString();
    path = path.substring(0, path.indexOf("/Android"));

    Toast.makeText(getApplicationContext(), "Creating " + path + "/MyFiles/File.txt", Toast.LENGTH_LONG).show();

    File file = new File(path + "/MyFiles/File.txt");
    try {
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

But I get this error on the instruction file.createNewFile():

2019-12-13 00:54:18.945 26573-26573/com.... W/System.err: java.io.IOException: Permission denied

I think my AndroidManifest is ok

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com...">

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

    <application...

I've granted all the permissions in settings

enter image description here

devpelux
  • 2,492
  • 3
  • 18
  • 38
  • In your case, simply get rid of `path.substring(0, path.indexOf("/Android"))`. Not only will this give you a location that will work on Android 10 and higher, but you will not need permissions. Moreover, you are assuming that, across ~2.5 billion devices and ~26,000 device models, that there will always be `/Android` in `getExternalFilesDir()`, and that would not seem to be a safe assumption. – CommonsWare Dec 13 '19 at 00:29
  • If I want to use MediaStore to save my files, how to do it? I cannot found any correct guide. They are essentially recorded audio files (I used txt only for an example), that an user want to copy or share, and find them in "Android/data/..." is strange. – devpelux Dec 13 '19 at 01:21
  • Call `insert()` on a `ContentResolver`, with a `Uri` to the appropriate media type and location (e.g., `MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)`). That will return a `Uri` which you can use with `openOutputStream()` on a `ContentResolver` to get an `OutputStream`, into which you can write your content. [This sample app](https://gitlab.com/commonsguy/cw-android-q/tree/vFINAL/ConferenceVideos) (from [this book](https://commonsware.com/Q)) demonstrates the technique, though I am saving a video, not audio content. – CommonsWare Dec 13 '19 at 01:26

1 Answers1

1

Make sure you are creating the file in an existing directory. Also, you may need to request permission at run-time as required for API >= 23.

See https://developer.android.com/training/permissions/requesting

Christilyn Arjona
  • 2,173
  • 3
  • 13
  • 20