android - 为什么正在捕获的图像返回 null?
问题描述
我有这个应用程序,一旦用户使用相机应用程序拍照,它会自动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
?
解决方案
推荐阅读
- mysql - 如何使用 MySQL 获得取决于 id 的价格
- assembly - 如何修复 Microsoft 16 位链接器上的错误 L2029?
- unit-testing - RPC 在单元测试中被阻塞
- node.js - 从 node.js 在 mysql 中创建存储过程
- python-3.x - 以最快的速度列出嵌套字典
- java - 在java中,'for(int i=0; i
}' 和 'array = 新 [数组.长度]'? - javascript - TypeScript:如何在不手动声明的情况下创建一个包含基类所有方法的包装类?
- postgresql - 如何配置postgresql服务器
- angular - 为什么我的模态可以从一个选项卡窗格打开,而不是从我的 Angular 页面中的另一个?
- daml - DAML 沙盒错误:错误:注册表项 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion' 的值为 '1.8',但需要 '1.7'