简体   繁体   中英

Writing to the external storage is not working anymore on Nougat

I wrote a little app to learn how to write and read files. It worked, but now I can't write files any more..

1.I added to Manifest:

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

2.In MainActivity

// permissions array:
final String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
// permission code for action multiple permission request:
private static final int ALL_PERMISSIONS = 101;

3.OnCreate (MainActivity):

// check multiple permissions:
    ActivityCompat.requestPermissions(this, permissions, ALL_PERMISSIONS);

4.onRequestPermissionsResult (@override MainActivity ):

    @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    // for PERMISSION_CODE:
    switch (ALL_PERMISSIONS){
        case 101:
            // if grantResults is populated:
            if(grantResults.length > 0){
                // 1° permission check:
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    reportText.append("\n GPS permission granted");
                }
                else{ reportText.append("\n no GPS permissions"); }
                // 2° permission check. NOTE: write permission is such as READ permission?
                if(grantResults[1] == PackageManager.PERMISSION_GRANTED){
                    reportText.append("\n WRITE permission granted");
                }
                else{ reportText.append("\n no WRITE permissions"); }
                if(grantResults[2] == PackageManager.PERMISSION_GRANTED){
                    reportText.append("\n READ permission granted");
                }
                else{reportText.append("\n no READ permissions"); }
            }
    }
}

5. OnButtonClickSave():

public void onButtonSave(View view){
    // get text from EditView
    String textToSave = inputText.getText().toString();
    dir.mkdir();
    // check if folder exists:
    if (!dir.exists()){
        // if not, create it:
        dir.mkdir();
    }
    try {
        // write to file:
        FileOutputStream fos = new FileOutputStream(file, true);
        fos.write(textToSave.getBytes());
        fos.close();
        // add files to explorer (update device explorer)
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(uri);
        sendBroadcast(intent);
        // send message to activity-layout:
        reportText.append("\n file saved" + file.toString());
    } catch (IOException e) {
        // else error
        e.printStackTrace();
        reportText.append("\n file not saved");
    }
}

I setted also a TextView (called report as you can see in code) that give all permissions granted, but I can't save any file. (FILE NOT FOUND).

What is wrong with this? (this app was working until some days ago)..

EDIT:

Sorry for that, I missed to give you file paths (onCreate):

        // create dir, file and Uri:
    dir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filepath);
    file = new File(dir, fileName);
    uri = Uri.fromFile(file);

After some test I found the way to fix this issue. I'm not completely sure about my conclusions but it's quite logic.

When I tried to save a file, I tried before to create relative folder, and this is the way to do that (in every example, tutorial or support document). And that was working...

(there is no need to use a "file provider" as suggested by @R7G) From official doc: "FileProvider is a special subclass of ContentProvider that facilitates secure sharing of files associated with an app"

During some test I deleted Donwload folder in my device internal-storage. After doing that the code started to give errors.

MISTAKE: I tried to create directly a sub-folder (fileFolder) inside a folder that exixted any more (Donwload):

dir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filepath);
dir.mkdir();

SOLUTION: In my case (subfolder inside a folder), you must be sure to create every parent folder before its child.

File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
dir.mkdir();
subDir = dir = new File (dir, filepath);
subDir.mkdir();

.... and so on (if other subfolders)

Hope this can help. If someone can confirm or extend my answer, it would be great.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM