简体   繁体   中英

How create directory using URI (Android)?

In my application i want to create subdirectories in choosen directory. Im using SAF (Storage Access Framework): choose directory and create one subdirectory works fine.

Choose directory:

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, REQUEST_CODE_PATH_TO_DATA);

Create subdirectory:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_OK) {
        return;
    }

    if (requestCode == REQUEST_CODE_PATH_TO_DATA) {
        if (data == null) {
            return;
        }

        DocumentFile pickedDir = DocumentFile.fromTreeUri(getActivity(), data.getData());
        getActivity().grantUriPermission(getActivity().getPackageName(), data.getData(), Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        getActivity().getContentResolver().takePersistableUriPermission(data.getData(), Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        pickedDir.createDirectory("Portfolio");
        String pathToPickedDir = "";
        for (DocumentFile file : pickedDir.listFiles()) {
            if (file.isDirectory() && file.getName().endsWith("Portfolio")) {
                pathToPickedDir = file.getUri().toString();
            }
        }
    }
}

URI from pickedDir is:

content://com.android.externalstorage.documents/tree/314E-7741%3ADCIM

And URI from created subdirectory "Portfolio" is:

content://com.android.externalstorage.documents/tree/314E-7741%3ADCIM/document/314E-7741%3ADCIM%2FPortfolio

And then when im trying to create subdirectory in "Portfolio" i can't do that, because the directory is created in the folder that was initially selected, not in the "Portfolio" folder.

DocumentFile pickedDir = DocumentFile.fromTreeUri(getActivity(), pathToPickedDir);
pickedDir.createDirectory("Patient");

What am I doing wrong? Thank you for your help.

Only way that i found is using "for" cycle:

        for (DocumentFile file : pickedDir.listFiles()) {
            if (file.isDirectory() && file.getName().equals("Portfolio")) {
                file.createDirectory("Subdirectory");
            }
        }

The following should work in your case:

DocumentFile portfolioDir = pickedDir.createDirectory("Portfolio");
portfolioDir.createDirectory("Patient");

In your code, you are not using the directory object returned by DocumentFile.createDirectory(), which is the object of the newly created directory, in which you want to create a sub-directory.

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