问题
[Rewrite, based on comments]
Simplified example:
rootUri
is obtained by ACTION_OPEN_DOCUMENT_TREE
. Then I create a folder (or more nested folders):
val rootTree = DocumentFile.fromTreeUri(context, rootUri) // rootTree.name == "treeRoot"
val childTree = rootTree.createDirectory("ChildDir1") // childTree.name == "ChildDir1"
val childUriStr = childTree.uri.toString()
I store childUriStr
into local database so I can later recreate childTree
. childUriStr
contains all elements needed: authority
, rootTree
documentId and childTree
documentId. So childTree
could be recreated by:
val childUri = Uri.parse(childUriStr)
val childTreeCopy = TreeDocumentFile(
DocumentFile.fromTreeUri(context, childTree), // equals rootTree
context,
childUri
)
But the TreeDocumentFile()
constructor is package-private and only used internally and by DocumentFile.fromTreeUri()
.
Workaround 1 (slow):
var childTree = DocumentFile.fromTreeUri(context, childUri)!! // rootTree
// get subfolders
val subfolders = DocumentsContract.getDocumentId(childUri)
.substringAfter(
// root documentId
DocumentsContract.getDocumentId(childTree.uri))
).trim('/').split('/')
// move down the folder structure
subfolders.forEach { childTree = childTree.findFile(it)!! }
// result
childTree
Workaround 2 (information about rootTree is lost):
val childAsRootUri = DocumentsContract.buildTreeDocumentUri(
childUri.authority,
DocumentsContract.getDocumentId(childUri)
)
var childAsRootTree = DocumentFile.fromTreeUri(context, childAsRootUri)!!
Here, the tree is planted at subfolder so I can not use childAsRootTree.parent
, cannot resolve name childAsRootTree.name == null
and probably some other hickups - definitely not recommended. DocumentFile.fromSingleUri()
also loses too much functionality compared to TreeDocumentFile
.
Workaround 3 (additional code to maintain):
Writing my own wrapper based on TreeDocumentFile
Use case (no need to read)
Please note that what is described above is a simplified example. A potential use case, similar to mine would be:
User chooses a single file or a folder with multiple files via in-app file explorer (step 1). A root file of in-app file explorer is obtained by ACTION_OPEN_DOCUMENT_TREE
. User can process the files and then the processed files are saved in the same directory if the user selected folder in step 1, or next to the selected file in a new folder if user selected file in step 1 (this requires accessing parent folder of the selected file). User can later decide to choose a different arrangement of saved files.
来源:https://stackoverflow.com/questions/59831233/how-to-get-child-treedocumentfile-from-child-uri