0ptl
0ptl

Reputation: 53

Android Kotlin (beginner) - using File() with Uri returned from ACTION_GET_CONTENT

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?

Upvotes: 4

Views: 4821

Answers (2)

greenapps
greenapps

Reputation: 11214

You are not supposed to use the File class for an uri obtained by ACTION_GET_CONTENT.

Nor are you supposed to deduce a file path from that uri to use the File class on it.

Instead you should directly open an inputstream for the obtained uri if you want to read it contents.

Upvotes: 1

Charles Shiller
Charles Shiller

Reputation: 1048

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.

Upvotes: 3

Related Questions