onActivityResult is not called (Kotlin) - android

I need help. On my onCreate() I have this code:
takePhotoDialog = DialogGetPhotoFrom.getInstance().apply {
setListener(object : DialogGetPhotoFrom.DialogListener {
override fun onTakeFromGallery() {
Log.v("ProjectDetails", "onTakeFromGallery called")
val intent = Intent().apply {
type = "image/*"
action = Intent.ACTION_GET_CONTENT
}
startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_PICK_IMAGE)
}
override fun onTakePhoto() {
dispatchTakePictureIntent()
}
})
}
projectDetails_pickImage.setOnClickListener { takePhotoDialog?.show(supportFragmentManager) }
An on my onActivityResult, I wrote:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_PICK_IMAGE -> {
Log.v("ProjectDetails", "REQUEST_PICK_IMAGE called")
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
try {
val inputStream = contentResolver.openInputStream(data.data)
val bitMap = BitmapFactory.decodeStream(inputStream)
projectDetails_image.setImageBitmap(bitMap)
// TODO Save image URI to database
} catch (e: Exception) {
Toast.makeText(this, "Can't set background.", Toast.LENGTH_SHORT).show()
}
} else {
Log.v("ProjectDetails", "data is null")
}
}
}
}
}
The problem is, onActivityResult() doesn't fire when an image is selected. What should I do?

Solved it! The solution is to put the codes inside my onTakeGallery() function to a function that belongs to the Activity class. So my code will look like this:
takePhotoDialog = DialogGetPhotoFrom.getInstance().apply {
setListener(object : DialogGetPhotoFrom.DialogListener {
override fun onTakeFromGallery() {
dispatchSelectFromGalleryIntent()
}
override fun onTakePhoto() {
dispatchTakePictureIntent()
}
})
}
projectDetails_pickImage.setOnClickListener {
takePhotoDialog?.show(supportFragmentManager)
}
And the extracted codes goes here:
private fun dispatchSelectFromGalleryIntent() {
val intent = Intent().apply {
type = "image/*"
action = Intent.ACTION_GET_CONTENT
}
startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_PICK_IMAGE)
}

Related

Google ML Kit face detection can not identify faces from uri

I'm using google ml kit for face detection, then use bounding Box function to crop faces.
I successfully integrate cameras ,then want to add select from gallery function, which I successfully implement previous training app that I wrote in Java, yet I can find why App written in Kotlin can not identify image Uri from gallery.
I tried multiple methods InputImage.fromBirmap(), InputImage.fromFilePath() and InputImage.fromByteArray("use nv21"), and used Image View to display images with rotation degrees that seems perfect. You can find codes that initiated by on click method below, except InputImage.fromFilePath() and InputImage.fromByteArray("use nv21") which tried first, then delete the codes.
Also thank you before hand.
private fun selectImage() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 11)
}
#RequiresApi(Build.VERSION_CODES.N)
#Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
if (requestCode == 11) {
if (data != null){
val bitmap = getBitmapFromUri(data.data!!)
Log.d(TAG, "onActivityResult: ${data.data!!}")
val inputStream = contentResolver.openInputStream(data.data!!)
val exif = ExifInterface(inputStream!!)
val rotation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL
)
val rotationInDegrees: Int = exifToDegrees(rotation)
inputStream.close()
Log.d(TAG, "onActivityResult: rotation: $rotation")
if (bitmap != null) selectedImageAnalyser(bitmap, rotationInDegrees)
}
}
}
}
private fun exifToDegrees(exifOrientation: Int): Int {
return when (exifOrientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> {
90
}
ExifInterface.ORIENTATION_ROTATE_180 -> {
180
}
ExifInterface.ORIENTATION_ROTATE_270 -> {
270
}
else -> 0
}
}
private fun getBitmapFromUri(uri: Uri): Bitmap? {
var bitmap: Bitmap? = null
try {
bitmap = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O_MR1) {
val source = ImageDecoder.createSource(
contentResolver, uri
)
ImageDecoder.decodeBitmap(source)
} else {
MediaStore.Images.Media.getBitmap(contentResolver, uri)
}
} catch (e: IOException) {
e.printStackTrace()
}
return bitmap
}
private fun selectedImageAnalyser(bitmap: Bitmap, rotationDegree: Int) {
val mBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true)
val inputImage = InputImage.fromBitmap(mBitmap, rotationDegree)
val rotation = inputImage.rotationDegrees
Log.d(TAG, "onActivityResult: rotation: $rotation")
binding!!.ivFace.apply {
visibility = View.VISIBLE
setImageBitmap(inputImage.bitmapInternal)
}
faceDetector.process(inputImage)
.addOnSuccessListener { faces ->
if (faces.isNullOrEmpty()){
val croppedFace = cropToBox(bitmap,faces[0].boundingBox,rotation)
startEnrollDialog(croppedFace)
} else{
Log.d(TAG, "selectedImageAnalyser: face can not identified")
}
}
.addOnFailureListener { Log.d(TAG, "selectedImageAnalyser: \n\t Cause: ${it.cause} \n\t Message: ${it.message}") }
.addOnCompleteListener { }
}

Unable to capture image in android 11

i'm trying to capture image in android 11 device but request is keep cancelled. i have added also. still unable to capture image. pick image from gallery is working. image is not storing in Android/data folder.
i have added val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION) also still unable to create temp file in storage. please provide any solutions
private fun selectImage() {
imageUtils.createImageFile(applicationContext).let {
viewModel.setFileTempPath(it.absolutePath, "doc_name")
startActivityForResult(imageUtils.captureImage(applicationContext, it), 300)
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
300 -> when (resultCode) {
RESULT_OK -> {
Log.d("tmppath", data?.data.toString())
if (data != null && data.data != null) {
val selectedImage: Bitmap =
imageUtils.getBitmap(data.data, this#TaggingActivity)!!
viewModel.dataModel.selectedImagesArrayList.value.let {
if (it == null) {
viewModel.dataModel.selectedImagesArrayList.value = ArrayList()
}
val a = it
a?.add(
ImageDetailsToUpload(
"",
selectedImage,
Constant.CUSTOMER_GEO_TAG,
viewModel.dataModel.documentName.value,
viewModel.commonModel.currentLocation.value!!
)
)
viewModel.dataModel.selectedImagesArrayList.postValue(a)
}
} else {
if (viewModel.dataModel.tmpPath.value != null) {
imageUtils.getBitmapFromPath(viewModel.dataModel.tmpPath.value)
?.let { selectedImage ->
val a = viewModel.dataModel.selectedImagesArrayList.value
a?.add(
ImageDetailsToUpload(
"",
selectedImage,
Constant.CUSTOMER_GEO_TAG,
viewModel.dataModel.documentName.value,
viewModel.commonModel.currentLocation.value!!
)
)
viewModel.dataModel.selectedImagesArrayList.postValue(a)
} ?: run {
viewModel.commonModel.showToastTextView("Sorry Try Again..!")
}
} else {
viewModel.commonModel.showToastTextView("Sorry Try Again..!")
return
}
}
viewModel.dataModel.tmpPath.value = null
}
RESULT_CANCELED -> {
viewModel.setFileTempPath("", "")
Toast.makeText(this,"cancelled",Toast.LENGTH_LONG).show()
}
}
}
//Intent class
fun getCameraIntent(file: File): Intent {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file))
if (Build.VERSION.SDK_INT >= 24) {
try {
val m =
StrictMode::class.java.getMethod("disableDeathOnFileUriExposure")
m.invoke(null)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
} else {
takePictureIntent.putExtra("return-data", true)
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
val pickPhoto = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
val intents: ArrayList<Intent> = arrayListOf()
intents.add(takePictureIntent)
intents.add(pickPhoto)
val chooserIntent = Intent.createChooser(
intents.removeAt(intents.size - 1),
" Document Upload"
)
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(arrayOf<Parcelable>()))
return chooserIntent
}

Cannot see any image in my emulator in Kotlin

I am trying to select an image in an activity but as soon as I click to select, I get to the Device Folder but it has no picture in it. Please see my code below:
class AddPainting : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_painting)
}
fun select(view: View) {
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 2);
} else {
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
if(requestCode == 2) {
if(grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
val intent = Intent(Intent.ACTION_PICK);
intent.type = "image/*";
startActivityForResult(intent, 1);
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if(requestCode == 1 && requestCode == Activity.RESULT_OK && data != null) {
val image = data.data;
try{
val selectedImage = MediaStore.Images.Media.getBitmap(this.contentResolver, image);
imageView.setImageURI(data?.data);
}catch (e: Exception) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data)
}
fun save(view: View) {
}
}
This is what I see when it transfers me to pick a picture
Use your selectedImage bitmap to set in ImageView
imageView.setImageURI(data?.data);
to
imageView.setImageURI(selectedImage);

kotlin.KotlinNullPointerException File not founded, only in samsung devices

I used this method to get file from uri, it is work fine with all devices but only crash with samsung devices!
fun Activity.getFilePath(uri: Uri): File {
var cursor: Cursor? = null
return try {
val dataArray = arrayOf(MediaStore.Images.Media.DATA)
cursor = contentResolver.query(uri, dataArray, null, null, null)
val index = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor?.moveToFirst()
File(index?.let { cursor?.getString(it) })
} catch (e: Exception) {
throw KotlinNullPointerException("File not founded")
} finally {
cursor?.close()
}
}
get image from gallery
fun Activity.chooseImageFromGallery(withAskPermission: Boolean) {
if (isPermissionsGranted(Manifest.permission.READ_EXTERNAL_STORAGE)) {
val intent = Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST)
} else {
if (withAskPermission && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
PICK_IMAGE_REQUEST)
}
}
}
on Activity result
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && requestCode == PICK_IMAGE_REQUEST) {
uri = data?.data
file = uri?.let { activity?.getFilePath(it) }
//
}
}

While using the camera or gallery in app, it crashes on backButton press

I am trying to use the camera or gallery (as an alert) in an application for uploading documents. The app crashes if the back button is pressed and no image was selected.
private fun getImageFromCamera() {
val takePicture = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takePicture.resolveActivity(packageManager) != null) {
startActivityForResult(takePicture, TAKE_PICTURE)
}
}
private fun getImageFromGallery() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
if (intent.resolveActivity(packageManager) != null) {
startActivityForResult(Intent.createChooser(intent, "Select
Picture"), PICK_IMAGE)
}
}
There is no issue regarding the permission for the camera. I didn't post all the code.
onActivityResult:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PICK_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
try {
val inputStream1 = contentResolver.openInputStream(data.data!!)
bitmap = BitmapFactory.decodeStream(inputStream1)
mUploadPanCardImageButton!!.setImageBitmap(bitmap)
mUploadPanCardTextView?.visibility = View.GONE
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
}
}else if (requestCode == TAKE_PICTURE) {
if (resultCode == Activity.RESULT_OK) {
val extras1 = data.extras
bitmap = extras1!!.get("data") as Bitmap
mUploadPanCardImageButton!!.setImageBitmap(bitmap)
mUploadPanCardTextView?.visibility = View.GONE
}
}
}
Here is the Exception that I am getting:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=12345, result=0, data=null} to activity {in.inspiringwave.firstapp/in.inspiringwave.firstapp.UploadDocsActivity}:
java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter data at
android.app.ActivityThread.deliverResults(ActivityThread.java:4173) at
android.app.ActivityThread.handleSendResult(ActivityThread.java:4216) at
android.app.ActivityThread.-wrap20(ActivityThread.java)
Make your onActivityResult Nullable by putting ? for intent like this-
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

Categories

Resources