I am using a file picker to let the user choose a data input file (.txt). After some research, I finally found a solution that avoids any deprecated method, using ActivityResultLauncher:
Declaring the filePicker with:
private var filePicker: ActivityResultLauncher<String>? = null
Registering the file picker in my fragment's onAttach method, calling:
private fun registerFilePicker() {
filePicker = registerForActivityResult<String, Uri>(
ActivityResultContracts.GetContent()
) { uri: Uri? -> onPickFile(uri) }
}
Opening the file picker with:
private fun openFilePicker() {
val mimeType = "*/*"
filePicker!!.launch(mimeType)
}
Triggering action on the user's selected file:
private fun onPickFile(uri: Uri?) {
try {
requireActivity().contentResolver.openInputStream(uri!!).use { inputStream ->
inputStream?.let {
it.reader().useLines { lines ->
lines.forEach {
val mot = it.substringBefore(',')
if (!(mot in Mots))
importListLine.add(Import(mot, it.substringAfter(','), true ))
}
adapter?.setImportList(importListLine)
adapter?.notifyDataSetChanged()
binding.btnSave.isVisible = true
binding.btnCancel.isVisible = true
}
}
}
} catch (exception: IOException) {
}
}
This works pretty fine so far. But what I want now is to open the filepicker in my own directory uri, which should be feasible with something like:
putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri)
Can someone tell where this should be added to ?
It appears that to customize the intent (e.g. to define an initial uri to the picker), the best would be to override the createIntent method. I tried it but did not made it to a full proper functioning (my initial uri was ignored).
Meantime I found the following solution on medium.com by Abdul Hamid (thanks to him) that is both compact and works perfeclty for me:
If you are working in a fragment instead of main activity, just declare and initialize contentResolver like this: