I have this application where once the user takes a photo using the camera app, it will automatically set the ImageView
in the application to that captured image. I keep getting this error and it's causing my application to crash:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.company.example/com.company.example.Camera}: java.lang.NullPointerException
The error occurs here, specifically the foodBitmap
line:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val foodBitmap = Objects.requireNonNull(Objects.requireNonNull(data)!!.extras)!!["data"] as Bitmap
food_image.setImageBitmap(foodBitmap)
}
These are the two functions I'm using to capture the image. I have all the permissions set up properly:
private fun openCamera() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
// Ensure that there's a camera activity to handle the intent
takePictureIntent.resolveActivity(packageManager)?.also {
// Create the File where the photo should go
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
// Error occurred while creating the File
null
}
// Continue only if the File was successfully created
photoFile?.also {
photoURI = FileProvider.getUriForFile(
Objects.requireNonNull(applicationContext),
BuildConfig.APPLICATION_ID + ".provider",
photoFile
)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(takePictureIntent, 1)
}
}
}
}
@Throws(IOException::class)
private fun createImageFile(): File {
// Create an image file name
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${timeStamp}_", /* prefix */
".jpg", /* suffix */
storageDir /* directory */
).apply {
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = absolutePath
}
}
What am I doing wrong here? Why is data
in onActivityResult
null?