4

Using the FileChooser from Intent.ACTION_OPEN_DOCUMENT_TREE I want to be able to write a file in the location the user selects. Since the file chooser returns a Tree URI, I use a utility class, specifically the method FileUtil.getFullPathFromTreeUri, taken from this question to convert that URI to a usable android directory URI.

For example: content://com.android.externalstorage.documents/tree/0A17-1D03%3ATest

Converts to this: /storage/0A17-1D03/Test

This is the code I have so far:

@Override
public void onClick(View v) {
    Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    i.addCategory(Intent.CATEGORY_DEFAULT);
    startActivityForResult(Intent.createChooser(i, "Choose a directory"), FILE_CHOOSER_REQUEST_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_CHOOSER_REQUEST_CODE:
            if (data != null) {
                Log.i("URI", FileUtil.getFullPathFromTreeUri(data.getData(), getActivity()));
                dismiss();
            }
            break;
    }
}

How do I write a file at the location returned by FileUtil.getFullPathFromTreeUri? (E.g: /storage/0A17-1D03/Test)

Morgan
  • 907
  • 1
  • 13
  • 35

1 Answers1

2

Wrong approach.

Do away with that silly function getFullPathFromTreeUri().

Just create a DocumentFile instance for the obtained tree uri.

After that use createFile() on the instance.

Precise examples have been posted before.

Just do a little googling.

greenapps
  • 11,154
  • 2
  • 16
  • 19