hello friends, I am creating an application that when taking a photo captures the image in an imageView and saves it, the problem is that it throws me this error:
The lateinit property bitmap has not been initialized
I think I should initialize it in the onActivityResult, but I don’t know how since in this method I am using the following
binding.imageView.setImageURI (photo)
try converting my Uri (photo) to a Strirg as follows
bitmap = data? .Additional features? .get (photo.toString ()) as bitmap
binding.imageView.setImageBitmap (bitmap)
but the error persists
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK) {
// bitmap = data?.extras?.get(photo.toString) as Bitmap
//binding.imageView.setImageBitmap(bitmap)
binding.imageView.setImageURI(foto)
}
}
var foto: Uri? = null
private fun takePicture() {
var fos: OutputStream? = null
var file: File? = null
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val resolver = this.contentResolver
val fileName = ("${System.currentTimeMillis()}${"Image_Example"}")
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/MyApp")
// put(MediaStore.Images.Media.IS_PENDING, 1)
put(MediaStore.Images.Media.TITLE, "Nueva_imagen")
}
foto = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
val camaraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
camaraIntent.putExtra(MediaStore.EXTRA_OUTPUT, foto)
startActivityForResult(camaraIntent, TAKE_PICTURE)
try {
fos = foto?.let { resolver.openOutputStream(it) }
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
values.clear()
values.put(MediaStore.Images.Media.IS_PENDING, 0)
if (foto != null) {
resolver.update(foto!!, values, null, null)
}
} else {
val imageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString()
val fileName = ("${System.currentTimeMillis()}${".jpg"}")
file = File(imageDir, fileName)
try {
fos = FileOutputStream(file)
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
}
val save: Boolean = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
if (save) {
Toast.makeText(this, "Picture save successfully", Toast.LENGTH_SHORT).show()
}
fos?.run {
flush()
close()
}
if (fos != null) {
try {
fos.flush()
fos.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
if (file != null) {
MediaScannerConnection.scanFile(this, arrayOf(file.toString()), null, null)
}