我有这个应用程序,一旦用户使用相机应用程序拍照,它将自动将应用程序中的ImageView
设置为所捕获的图像。我不断收到此错误,并导致我的应用程序崩溃:
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
此处发生错误,特别是foodBitmap
行:
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)
}
这是我用来捕获图像的两个功能。我已经正确设置了所有权限:
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
}
}
我在这里做错了什么?为什么data
中的onActivityResult
为空?