3

I'm trying to open a file picker in android, select a json file then get the text from it. The app crashes after i select the file because it can not find the path.

I have tried adding external storage read / write permission and changing the path format

/// some Activity code
val myFileIntent=Intent()
.setType("*/*")
.setAction(Intent.ACTION_GET_CONTENT)
startActivityForResult(myFileIntent,10)

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val path = data!!.data.path
        val jsonContent = File(path).readText()
    }
Teodor Radu
  • 113
  • 1
  • 1
  • 9
  • Please post the stacktrace – luckyhandler Apr 29 '19 at 17:36
  • Hi, this might be of interest https://stackoverflow.com/a/36129285/235354 – jspcal Apr 29 '19 at 17:37
  • Caused by: java.io.FileNotFoundException: /document/raw:/storage/emulated/0/Download/reteta.json (No such file or directory) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:231) at java.io.FileInputStream.(FileInputStream.java:165) at kotlin.io.FilesKt__FileReadWriteKt.readBytes(FileReadWrite.kt:63) at kotlin.io.FilesKt__FileReadWriteKt.readText(FileReadWrite.kt:101) – Teodor Radu Apr 29 '19 at 17:50

2 Answers2

3

I'm trying to open a file picker in android

That is not a file picker. That allows the user to choose a piece of content, which may or may not be a file.

The app crashes after i select the file

You are not picking a file. You are picking a piece of content. That content is identified by a Uri, and the scheme of your Uri is content, not file.

Use ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. You can call readText() on that InputStream to read it in as text.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
2

This is my final working code :

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

        val path = data?.data
        val jsonSelectedFile =  contentResolver.openInputStream(path);
        val inputAsString = jsonSelectedFile.bufferedReader().use { it.readText() }

        Toast.makeText(this, "Json: " +  inputAsString , Toast.LENGTH_LONG).show()
    }

And for calling :

 importJsonButton.setOnClickListener {
            val myFileIntent = Intent()
                .setType("*/*")
                .setAction(Intent.ACTION_GET_CONTENT)

            startActivityForResult(myFileIntent,10)
        }
Teodor Radu
  • 113
  • 1
  • 1
  • 9