0
Hello I’m having this error in my code someone could help me solve this?
grateful in advance.
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at map.app.fragments.ReportFragment.putImgToBytearray(ReportFragment.kt:177)
Error line
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream)
code
private fun putImgToBytearray(): ByteArray {
val stream = ByteArrayOutputStream()
val drawable = this.imgThumb!!.drawable as BitmapDrawable
val bitmap = drawable.bitmap
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream)
return stream.toByteArray()
}
onActivityResult code
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == IMAGE_PICK_CODE && resultCode == RESULT_OK) {
try {
//Getting the Bitmap from Gallery
val bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, this.imageUri) as Bitmap?
this.imgThumb!!.setImageBitmap(bitmap)
this.pictureTaken = true
} catch (e:IOException) {
e.printStackTrace()
}
} else {
Toast.makeText(context, "Error loading image", Toast.LENGTH_LONG)
}
}
method to open the gallery and grab an image, yes it is an adaptation
fun openCamera() {
try {
val imageFile = createImageFile()
val callCameraIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if(callCameraIntent.resolveActivity(activity.packageManager) != null) {
val authorities = activity.packageName + ".fileprovider"
this.imageUri = FileProvider.getUriForFile(context, authorities, imageFile)
callCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
startActivityForResult(callCameraIntent, IMAGE_PICK_CODE)
}
} catch (e: IOException) {
Toast.makeText(context, "Could not create file!", Toast.LENGTH_SHORT).show()
}
}
Possible duplicate of What is Nullpointerexception and what are its main causes?
– Icaro Martins
Hello @Marc, your problem seems to be this line
val bitmap = drawable.bitmap
, apparently thatdrawable.bitmap
is returningnull
then when you make that callbitmap.compress(...)
the variablebitmap
this null why the error. As I have not yet ventured with the [tag:Kotlin] I can’t help you much more than that =P, check the contents of the variabledrawable
owns the propertybitmap
=D– Icaro Martins