We have reported some crashes from Android 9 and 10 devices when they try to read pdf file with this method:
fun getPdfImageFromUri(uri: Uri?, applicationContext: Context): String? {
var outputString: String? = null
uri?.let {
ByteArrayOutputStream().apply {
outputString = encodeToString(applicationContext.contentResolver.openInputStream(it)?.readAllBytes())
}
}
return outputString
}
and crash report: java.lang.NoSuchMethodError: No virtual method readAllBytes()[B in class Ljava/io/InputStream; or its super classes (declaration of 'java.io.InputStream' appears in /apex/com.android.art/javalib/core-oj.jar)
what could cause this problem ? Seems like it works fine on Android 11-13
Try this code:
fun getPdfImageFromUri(uri: Uri?, applicationContext: Context): String? {
var outputString: String? = null
uri?.let {
val inputStream = applicationContext.contentResolver.openInputStream(it)
val bytes = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
inputStream?.readAllBytes()
} else {
inputStream?.readBytes()
}
outputString = encodeToString(bytes)
}
return outputString
}
The problem was caused by the use of the readAllBytes()
method, which was introduced in Java 9. This method is not available on Android 9 and 10 devices, causing the java.lang.NoSuchMethodError to be thrown when the code is run on those devices.
Here are some links that support this information: