Reputation: 21
I want to open a file explorer and get selected file path in Kotlin Is there any guid for this purpose?
Upvotes: 1
Views: 3422
Reputation: 61
The most simple option to show a file explorer is to call to the "ACTION_GET_CONTENT" intent and get a code result (777 at the example) with "startActivityForResult", like this:
val intent = Intent()
.setType("*/*")
.setAction(Intent.ACTION_GET_CONTENT)
startActivityForResult(Intent.createChooser(intent, "Select a file"), 777)
Later, override the "onActivityResult" function in your activity and get the data only if the request code is the same that the "startActivityForResult" (777 at the example).
To save the URI from the selected file you can get "data?.data.toString()" and if you only need the path, use "data?.data?.path"
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 777) {
val filePath = data?.data?.path
}
}
Upvotes: 6