I'm very new to both Android and Kotlin/Java. I don't understand why my File()
method gets the error:
none of the following functions can be called with the arguments supplied.
I thought that what I have put should return the Uri obtained from the ACTION_GET_CONTENT
and that this should be enough to construct the File object. I'm trying to make an app that will load a txt file and display it. I'm hoping it's a really simple mistake somewhere:
fun showFileDialog() {
val fileintent = Intent(Intent.ACTION_GET_CONTENT)
fileintent.setType("text/plain")
fileintent.addCategory(Intent.CATEGORY_OPENABLE)
startActivityForResult(fileintent, FILE_SELECT_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == FILE_SELECT_CODE && resultCode == Activity.RESULT_OK) {
val selectedfile = File(data!!.data)
val readData = FileInputStream(selectedfile).bufferedReader().use { it.readText
textView.text = readData
}
}
}
I don't know if the rest of the posted code works either, but this error will not let me build it to test it. TIA for any help/pointers
RESOLVED:
The first answer explained why I was getting the error (hence, answering my question)
After getting help from second answer and comment below, (and more searching on SO; see links below) I changed my last 3 lines of code to:
val input: InputStream = getContentResolver().openInputStream(data!!.data)
val inputAsString = input.bufferedReader().use { it.readText() }
textView.setText(inputAsString)
and this is working well. Thank you!
LINKS:
Android: Getting a file URI from a content URI?
In Kotlin, how do I read the entire contents of an InputStream into a String?
While I can't comment on the rest of your code, data!!.data
returns a android.Uri
and File
takes a String[1].
You have to convert your Uri to a filename: something like File(data!!data.getPath());
[2]
[1]. It also takes a URI, but that's a Java.net.URI, rather than an Android.Uri.
[2]. You should still make sure that you're getting a Uri which points to a path on the filesystem. You may also have to do something like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With