Android Kotlin: Getting a FileNotFoundException with filename chosen from file picker?
You did not receive a file path, you received a Uri
. You have to use Uri
based APIs such as ContentResolver.openInputStream()
to access the contents at that Uri
as Android does not grant your app direct File
access to the underlying file (it could also be streamed from Google Drive or downloaded directly from the internet without your app being aware that this is happening):
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Selected a file to load
if ((requestCode == 111) && (resultCode == RESULT_OK)) {
val selectedFilename = data?.data //The uri with the location of the file
if (selectedFilename != null) {
contentResolver.openInputStream(selectedFilename)?.bufferedReader()?.forEachLine {
val toast = Toast.makeText(applicationContext, it, Toast.LENGTH_SHORT)
toast.show()
}
} else {
val msg = "Null filename data received!"
val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_LONG)
toast.show()
}
}
}
Here we can assume we get contents of the proper format by passing in the proper mime type to our request (as there is no requirement that a text file end in exactly the .txt
extension as part of its path):
val intent = Intent()
.setType("text/*")
.setAction(Intent.ACTION_GET_CONTENT)
startActivityForResult(Intent.createChooser(intent, "Select a file"), 111)
Which will automatically make any non text file unable to be selected.
How to get selected folder path from file picker in Android
You're not supposed to try to get a File
's path from a Uri
. You just use the Uri
itself as your reference to the file's location.
Besides, the user selected the location themselves, so they already know where it is.
Related Topics
How to Implement Endless List With Recyclerview
Repeat a Task With a Time Delay
What's the Difference Between the Various Methods to Get an Android Context
Drawing a Line/Path on Google Maps
Install_Failed_No_Matching_Abis When Install Apk
How to Prevent Custom Views from Losing State Across Screen Orientation Changes
Jdbc VS Web Service For Android
Passing Data Between a Fragment and Its Container Activity
What Is the Main Purpose of Settag() Gettag() Methods of View
Adding a Library/Jar to an Eclipse Android Project
How to Scale an Image in Imageview to Keep the Aspect Ratio