Alif Al-Gibran
Alif Al-Gibran

Reputation: 1246

Convert the content of an URI to a ByteArray in Android Studio using Kotlin

I need to choose a pdf from local storage and convert it to byteArray for firebase database path. I searched a lot but there was no answer to this question.

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if(requestCode == RC_SELECT_PDF && resultCode == Activity.RESULT_OK &&
        data != null && data.data != null) {
            val hereUrl:Uri = data.data
            var os = ByteArrayOutputStream()
            var inputStream = this@RegistrasiPengajarActivity?.contentResolver.openInputStream(hereUrl)
            var byteArray = inputStream.available()
    }
}

thats all a can do, i've selected the pdf but still have no idea how to convert it

Upvotes: 4

Views: 5951

Answers (2)

Alexander Egger
Alexander Egger

Reputation: 5300

Kotlin (since 1.3) provides the extension method InputStream.readBytes() for reading all bytes of an InputStream into a ByteArray.

In your case use:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
     if(requestCode == RC_SELECT_PDF && resultCode == Activity.RESULT_OK &&
            data != null && data.data != null){
            val hereUrl:Uri = data.data
            var os = ByteArrayOutputStream()
            var inputStream = this@RegistrasiPengajarActivity?.contentResolver.openInputStream(hereUrl)
            var byteArray = inputStream.readBytes()
        }
    }

Upvotes: 7

Ruchit Patel
Ruchit Patel

Reputation: 69

Try this:

var iStream = getContentResolver().openInputStream(uri)
var inputData = getBytes(iStream)

@Throws(IOException::class)
fun getBytes(inputStream:InputStream):ByteArray {
  val byteBuffer = ByteArrayOutputStream()
  val bufferSize = 1024
  val buffer = ByteArray(bufferSize)
  val len = 0
  while ((len = inputStream.read(buffer)) != -1)
  {
    byteBuffer.write(buffer, 0, len)
  }
  return byteBuffer.toByteArray()
}

Upvotes: 2

Related Questions