Search code examples
androidarrayskotlinfile-iofileoutputstream

Android: Writing byteArray into file


I'm trying to write a byteArray received from a server. This is my code

private fun writePdf(content: ByteArray) {

        val storageDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
        val file = File("${storageDir?.path}/", "${Date().time}Download.pdf")

        try {
//           file.writeBytes(archivo)
            val os = FileOutputStream(file, false)
            os.write(content)
            os.flush()
            os.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        val intent = Intent(Intent.ACTION_VIEW)
        val uri = FileProvider
            .getUriForFile(
                this,
                this.packageName + ".fileprovider",
                file)
        intent.setDataAndType(uri, "application/pdf")
        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP

        try{
            startActivity(intent)
        }catch (e: Exception){
            e.printStackTrace()
            Toast.makeText(this, "Error", Toast.LENGTH_LONG)
                .show()
        }
    }

The problem is that when the pdf opens it is blank, like nothing has been written.

  • I've tried writing with FileOutputStream and File.writeBytes.
  • I've checked the byteArray (in case is corrupted or something) and it has no problems.
  • I've checked the length() of the file before and after writing, and it's length increases accordingly.

Thanks, any kind of help is appreciated.


Solution

  • I finally found the problem, and solution. Everything with the code above was okay; the problem was that the flags for the intent to visualize the PDF were wrong. Instead of:

    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
    

    It should be:

    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)