After much try and study, I was able to figure it out. First, the variable data from Intent will always be null so, therefore, checking for !null
will crash your app so long you are passing a URI to startActivityForResult.Follow the example below.
I will be using Kotlin.
Open the camera intent
fun addBathroomPhoto(){
addbathroomphoto.setOnClickListener{
request_capture_image=2
var takePictureIntent:Intent?
takePictureIntent =Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if(takePictureIntent.resolveActivity(activity?.getPackageManager()) != null){
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
// Error occurred while creating the File
null
}
if (photoFile != null) {
val photoURI: Uri = FileProvider.getUriForFile(
activity!!,
"ogavenue.ng.hotelroomkeeping.fileprovider",photoFile)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
photoURI);
startActivityForResult(takePictureIntent,
request_capture_image);
}
}
}
}`
Create the createImageFile().But you MUST make the imageFilePath variable global. Example on how to create it is on Android official documentation and pretty straightforward
Get Intent
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == 1 && resultCode == RESULT_OK) {
add_room_photo_txt.text=""
var myBitmap=BitmapFactory.decodeFile(imageFilePath)
addroomphoto.setImageBitmap(myBitmap)
var file=File(imageFilePath)
var fis=FileInputStream(file)
var bm = BitmapFactory.decodeStream(fis);
roomphoto=getBytesFromBitmap(bm) }}
The getBytesFromBitmap method
fun getBytesFromBitmap(bitmap:Bitmap):ByteArray{
var stream=ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
return stream.toByteArray();
}
I hope this helps.