Issue
So everything is worling good camera is opening and also permission dialog is opening if there i no permission, but the image is not getting displayed in the image view. because i am getting null on result.data?.data
This is my function to create path for image captured and to open camera
fun displayCamera(activity: Activity) {
val destPath: String? = Objects.requireNonNull(
Objects.requireNonNull(activity).getExternalFilesDir(null)!!
).absolutePath
val imagesFolder = File(destPath, activity.resources.getString(R.string.app_name))
try {
imagesFolder.mkdirs()
val imgFile = File(imagesFolder, Date().time.toString() + ".jpg")
val imagePath = FileProvider.getUriForFile(
activity, "com.example.shoppinglist" + ".provider", imgFile
)
val intent = Intent(ACTION_IMAGE_CAPTURE)
intent.putExtra(EXTRA_OUTPUT, imagePath)
cameraResult.launch(intent)
} catch (e: Exception) {
e.printStackTrace()
}
}
2.This is my registerForActivity Result variable
private val cameraResult = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
binding.profilepic.setImageURI(result.data?.data)
}
}
3.This is the code where i am calling this function on button click
if (checkPermissions(this@RegistrationActivity)) {
displayCamera(this@RegistrationActivity)
} else {
requestPermission(requestMultiplePermissionLauncher)
}
Solution
Your code seems to be fine but sometimes there are issue with the FileProvider
if you are integrating it with the static package name and storage permission as well with different android versions.
You can try the below code which is working fine. I have saved the image bitmap to the storage and fetch the absolute path as imagePath
and after fetching the path i am setting the same inside imageView
.
Just change your code with the below code.
private fun displayCamera() {
val intent = Intent(ACTION_IMAGE_CAPTURE)
cameraResult.launch(intent)
}
cameraResult = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
val imageBitmap = result.data?.extras?.get("data") as Bitmap
val imagePath = saveImageToStorage(imageBitmap)
// Here you can insert this imagePath into your room database.
binding.profilepic.setImageURI(Uri.parse(imagePath))
}
}
private fun saveImageToStorage(bitmap: Bitmap): String? {
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
val imageFileName = "JPEG_$timeStamp.jpg"
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return try {
val imageFile = File(storageDir, imageFileName)
val fos = FileOutputStream(imageFile)
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)
fos.close()
imageFile.absolutePath
} catch (e: IOException) {
e.printStackTrace()
null
}
}
Answered By - Khush Parmar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.