Home > front end >  Problem using android storage access framework with sd card and with local files directory
Problem using android storage access framework with sd card and with local files directory

Time:12-09

I am wanting to use Android Scoped Storage for accessing both the local files directory and the SD card. My problem is with using the same functions to access both, for which I need the Uri for the local files directory.

I would have thought that the first two lines of code below would give me the Uri of the local files directory, but the third line, which is how I would use the Uri, raises an exception with this detail message:

  • Invalid URI: file:///data/user/0/tl.listmster2/files

          val file = DocumentFile.fromFile(context.filesDir)
          val uri = file.uri
          val dir = DocumentFile.fromTreeUri(context, uri)
    

I'm sure that there a workarounds, but it would be really helpful to get a valid Uri of the local files directory, if anyone has any ideas? Thanks in advance.

CodePudding user response:

My problem is with using the same functions to access both, for which I need the Uri for the local files directory

My interpretation is that by "the same functions to access both", you were planning on using fromTreeUri() for both documents and files. That will not work. fromTreeUri() only works with a document tree Uri.

My guess is that those "same functions" should be taking a DocumentFile as input, not a Uri. Code outside of those functions can know where the DocumentFile came from (fromFile(), fromTreeUri(), or fromSingleUri()). Those functions can deal with the DocumentFile abstraction, using methods like isDirectory() and listFiles() to traverse the contents as needed.

but it would be really helpful to get a valid Uri of the local files directory

There is no Uri based off a File that works with fromTreeUri().

CodePudding user response:

You should use ACTION_OPEN_DOCUMENT_TREE to let the user pick any directory from device or removable micro sd card.

Or ACTION_OPEN_DOCUMENT for files.

That is how you use SAF.

  • Related