My application has user pick a public directory (with Intent.ACTION_OPEN_DOCUMENT_TREE) to make a directory to save files that can be later extracted from the device. I also want to persist the path to the created directory to make it easier to access from the app.
For this I tried using File.mkdir() and Files.createDirectory(), neither of which managed to create the directories, so I decided to use DocumentFile as shown below:
fun saveFileDirectory(uri: Uri) { val chosenDirectory = DocumentFile.fromTreeUri(applicationContext, uri) if (chosenDirectory != null) { val newDirectory = chosenDirectory.createDirectory("newDirectory") newDirectory?.createDirectory("dir1") newDirectory?.createDirectory("dir2") val newUri = newDirectory?.uri //persisting the path viewModelScope.launch { applicationContext.dataStore.updateData { data -> data.copy(saveFileDirectory = newUri!!) } } }
This code successfully creates directories and persists the Uri to the created directory, but when I use that persisted Uri as initial uri for the file picker, the directory that was chosen by the user (which is a parent directory to the created directory) gets opened instead.
For example, user picks "/save" directory, so the input Uri is
content://com.android.externalstorage.documents/tree/primary:save
function saveFileDirectory will save the following path:
content://com.android.externalstorage.documents/tree/primary:save/document/primary:save/newDirectory
Then, the Uri is read into a variable named localSaveFileDirectory and used as an initial Uri for the file picker like this:
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { addCategory(Intent.CATEGORY_OPENABLE) putExtra(Intent.EXTRA_TITLE, "test.csv") putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.withAppendedPath(localSaveFileDirectory, "dir1")) type = "*/*" } launcherRead.launch(intent)
However, when user tries to pick a file, "/save" directory is opened.
I want it to open "/save/newDirectory" instead.