Delin Mathew
Delin Mathew

Reputation: 279

Kotlin Open file on button click

I am new to Kotlin. Can someone please tell me how to open a file on click of a button? Is there some command like:

Button.setOnAction {
File.Open(*//specified file path*)  
        }

I am using Kotlin for Java development and not for andriod. I have a .fxml file where I have defined this button and I need to define the above feature in a kotlin (.kt) file. Thank you.

Upvotes: 0

Views: 4319

Answers (2)

Beltran Rodriguez
Beltran Rodriguez

Reputation: 36

If you need to use this selectedFile path (@Rizkita answer) to read a text file, in onActivityResultfunction add something like this (Kotlin):

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 111 && resultCode == AppCompatActivity.RESULT_OK) {
            val selectedFile = data?.data //The uri with the location of the file

            // Get the File path from the Uri

            println(selectedFile?.lastPathSegment)
            val path = selectedFile?.lastPathSegment.toString().removePrefix("raw:")
            println(path)
            text_reader.setText(getTextContent(path))
        }
    }


fun getTextContent(pathFilename: String): String {

    val fileobj = File( pathFilename )

    if (!fileobj.exists()) {

        println("Path does not exist")

    } else {

        println("Path to read exist")
    }

    println("Path to the file:")
    println(pathFilename)

    if (fileobj.exists() && fileobj.canRead()) {

        var ins: InputStream = fileobj.inputStream()
        var content = ins.readBytes().toString(Charset.defaultCharset())
        return content

    }else{

        return "Some error, Not found the File, or app has not permissions: " + pathFilename
    }
}

Note that in my example text_reader is just the id of a TextView object in the .xml layout file.

Upvotes: 0

Rizkita
Rizkita

Reputation: 98

In your activity

btnBack.setOnClickListener {

    val intent = Intent()
            .setType("*/*")
            .setAction(Intent.ACTION_GET_CONTENT)

    startActivityForResult(Intent.createChooser(intent, "Select a file"), 111)

}

still in your activity, insert this to catch the result

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == 111 && resultCode == RESULT_OK) {
        val selectedFile = data?.data //The uri with the location of the file
    }
}

reference

Upvotes: 1

Related Questions