11

Task: Upload an image which the user can choose from the device.

How can I open the file chooser window on a button press in an Android app using Kotlin?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Amita
  • 195
  • 1
  • 1
  • 13

2 Answers2

22

In your activity, add the button click to add an intent:

btnBack.setOnClickListener {

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

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

Set a custom requestCode, I set 111.

Add the onActivityResult in your activity 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
    }
}

Now selectedFile will contain the location of what they selected.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Derek
  • 2,927
  • 3
  • 20
  • 33
0

I am using it in a PDF reader inside of a Fragment.

My code (without defining the correct directory to choose my file):

val selectedFile = data?.data // The URI with the location of the file <p>
pdfView.fromUri(selectedFile).load() // Show the selected file

// Fragment view
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {

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

    startActivityForResult(Intent.createChooser(intent, "Select a file"), 111)
    return inflater.inflate(R.layout.fragment_sat, container, false)
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Uchoa
  • 11
  • 1
  • What do you mean by *"the correct directory to choose my file"*? The location the file dialog shows when it opens? Or something else? Can you elaborate? – Peter Mortensen Oct 12 '22 at 16:43