Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 978
0ptl Avatar asked Oct 12 '25 23:10

0ptl


1 Answers

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.

like image 63
Charles Shiller Avatar answered Oct 14 '25 12:10

Charles Shiller