4

I would like to know how to use "Storage Access Framework" to create new folder on SD card. If you give me the code it would be very good. I have already searched other questions and answers but not found how to.

Add some codes that already work per "CommonsWare" answer. Note that is the only way I found that it can make new folder in sd card on my phone SS A5 with Android OS 5.1.1

    public void newFolder(View view)
    {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        startActivityForResult(intent, NEW_FOLDER_REQUEST_CODE);
    }

    private static final int NEW_FOLDER_REQUEST_CODE = 43;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        super.onActivityResult(requestCode, resultCode, resultData);

        Uri currentUri = null;

        if (resultCode == Activity.RESULT_OK)
        {
            if (requestCode == NEW_FOLDER_REQUEST_CODE)
            {
                if (resultData != null) {
                    currentUri = resultData.getData();
                    DocumentFile pickedDir = DocumentFile.fromTreeUri(this, currentUri);
                    DocumentFile newDir = pickedDir.createDirectory("MyFolder");
                    textView.setText(newDir.getName());
                }
            }
        }
    }

1 Answers1

8

You cannot create "create new folder on SD card". You can create a new folder inside some other folder that the user chooses, but you cannot force the user to choose removable storage.

To create a new folder inside of some other folder, this should work:

  1. Start an activity with startActivityForResult() on an ACTION_OPEN_DOCUMENT_TREE Intent, to allow the user to choose a folder. Include FLAG_DIR_SUPPORTS_CREATE to ensure that you can create something new in the folder.

  2. In onActivityResult(), wrap the Uri that you get in a DocumentFile, then call createDirectory() on it to create a new folder as a child of whatever the user chose.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 2
    CommonsWare: an example would be really appreciated. – user6159419 Oct 20 '20 at 13:29
  • @user6159419: The question seems to contain one. – CommonsWare Oct 20 '20 at 15:40
  • I was not sure about flag...FLAG_DIR_SUPPORTS_CREATE. can you guide where and how it can be declared. – user6159419 Oct 20 '20 at 16:56
  • @user6159419: That appears to be a mistake on my part. That does not appear to be an `Intent` flag. I updated the answer to strike out that particular part. I apologize for my mistake! – CommonsWare Oct 20 '20 at 18:06
  • 1
    You can 'wrap the Uri that you get in a DocumentFile' by calling DocumentTree.fromTreeUri and pass the uri and context as parameters - DocumentFile.fromTreeUri(context, uri) – clementiano Aug 30 '21 at 13:04
  • Yea can we get an example, i dont have android studio but still code from scratch in java, please. – J. M. Jan 30 '22 at 19:34