onActivityResults reseting values - android

I'm testing one functionality of an app in different devices and it happens in one of them:
When I calls onActivityResult, it works normally but in the second time it's called, it reset the previous data registered in the last call. It works normally in most of devices but this one exceptionally cleans the view when comes from activity result.
So basically when I selected the second image either from gallery or for camera intent, it resets the previous selected file.
This is how the data it's being retrieved:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(resultCode == RESULT_OK) {
val selectedImage: Uri?
if(requestCode == GALLERY_1 || requestCode == GALLERY_2 || requestCode == GALLERY_3) {
selectedImage = data!!.data
configImagePersistentPermission(selectedImage)
} else {
val bitmap = data!!.extras!!.get("data") as Bitmap
selectedImage = configImagePathUri(requireContext(), bitmap)
}
try {
when (requestCode) {
GALLERY_1 -> {
binding.imageDoc1.setImageURI(selectedImage)
configResetImageView(0)
}
CAMERA_1 -> {
binding.imageDoc1.setImageURI(selectedImage)
configResetImageView(0)
}
GALLERY_2 -> {
binding.imageDoc2.setImageURI(selectedImage)
configResetImageView(1)
}
CAMERA_2 -> {
binding.imageDoc2.setImageURI(selectedImage)
configResetImageView(1)
}
GALLERY_3 -> {
binding.imageDoc3.setImageURI(selectedImage)
configResetImageView(2)
}
CAMERA_3 -> {
binding.imageDoc3.setImageURI(selectedImage)
configResetImageView(2)
}
}
imageList.add(selectedImage.toString())
} catch (e: Exception){
e.printStackTrace()
}
}
}
How to prevent losing the previous recorded data in this scenario?
Thanks in advance

Related

onActivityResult deprecated, is there alternative (KOTLIN)

Currently I am working on a project for my college, and i have discovered that onActivityResult is deprecated. What can be done to handle it?
This is my code that troubles me
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
val result = CropImage.getActivityResult(data)
if (resultCode == RESULT_OK) {
image = result.uri
Glide.with(this).load(image).into(binding.imgPick)
} else {
Snackbar.make(
binding.root,
"Image not selected",
Snackbar.LENGTH_SHORT
).show()
}
}
}
I tried to find a solution on stackoverflow and already tried to implement couple of thing but with no luck.
You can use the following way :
fun openActivityForResult() {
startForResult.launch(Intent(this, AnotherActivity::class.java))
}
val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
val intent = result.data
// Handle the Intent
//do stuff here
}
}
You can use this in activity or fragment.
First define intent result launcher.
var picker: ActivityResultLauncher<Intent>
then
picker = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK && it.data != null) {
//add your code here
}
}
And now launch your activity.
val intent = Intent(context, ImagePickerActivity::class.java)
picker.launch(intent)

onActivityResult not getting called after changing the intent for (Save the full-size photo)

Im following the official documentation to capture the image and gets its path.
https://developer.android.com/training/camera/photobasics
I have write 100% same code as the documentation say, but two weird things are happing when I write the simple intent
private fun dispatchTakePictureIntent() {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
try {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
} catch (e: ActivityNotFoundException) {
// display error state to the user
}
}
The OnAcivityResult is getting called
But when I change the intent into
private fun dispatchTakePictureIntent() {
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 {
val photoURI: Uri = FileProvider.getUriForFile(
this,
"com.example.android.fileprovider",
it
)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
}
}
}
}
It does get called anymore.
Here is my OnAcivityResult code
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == OPEN_CAMERA)
if(resultCode == RESULT_OK && data != null) {
// not getting called
}
if(requestCode == OPEN_GALLERY)
if(resultCode == RESULT_OK && data != null) {
val image: Uri = data.data!!
openCropImageView(image)
}
if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
val uri = UCrop.getOutput(data!!)
val imgFile = File(uri?.path)
if (imgFile.exists()) {
val myBitmap = BitmapFactory.decodeFile(imgFile.absolutePath)
binding.previewImage.setImageBitmap(myBitmap)
}
}
}
any help, please.
Edit: Apparently its working fine on a pixel 5 running on android 11
emulator and its not working on Redmi note 5 running on android 8

How can I pass a variable control name to findViewById in Kotlin?

I am trying to learn Kotlin and I'm building a simple example as I go. I have 3 image buttons that open the camera and take a photo. The thumbnail is then set into an ImageView. I've used the examples from https://developer.android.com/training/camera/photobasics?hl=en to get the basics working (figuring if I can make it work for one, it'll work for all. It does indeed work for one, but I can't figure out how to make it one function that drops the thumbnail into the correct ImageView.
Inside my onCreate I have the listener for each of the buttons that will invoke the camera:
camRead1.setOnClickListener {dispatchTakePictureIntent() }
camRead2.setOnClickListener {dispatchTakePictureIntent() }
camRead3.setOnClickListener {dispatchTakePictureIntent() }
And I took the sample from the url above:
val REQUEST_IMAGE_CAPTURE = 1
private fun dispatchTakePictureIntent() {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
try {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
} catch (e: ActivityNotFoundException) {
// display error state to the user
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val thumb: ImageView = findViewById(R.id.thumbRead1)
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
val imageBitmap = data.extras.get("data") as Bitmap
thumb.setImageBitmap(imageBitmap)
}
}
and pasted it into my class MainActivity, and after I replaced imageView in the override function with a variable (thumb) and added the super, it worked perfectly for the first one.
However, I am trying to get 3 photos, read1, read2, and read3 which each need to display the thumb in thumbRead1, thumbRead2 and thumbRead3. I can't figure out how the onActivityResult is executed since the call inside dispatchTakePictureIntent is calling startActivityForResult (especially as Android Studio says that startActivityForResult is deprecated).
Obviously, once onActivityResult executes, I can see that thumb defines R.id.thumbRead1 and receives imageBitmap but I don't understand how I can make it aware of the button that was clicked.
Without understanding how onActivityResult is called, I'm thinking that if I can do something like:
findViewById(R.id("thumbRead" + imgID))
to define the specific ImageView that I want the photo pasted into. Am I on the right track here? If not, what is the recommended way of doing this?
Note they've recently added what's supposed to be a cleaner way of starting other activities for results and getting the results, explained here. But since you're already doing it the traditional way, I'll explain how to get that working.
I think the easiest thing to do in this situation is just make more request codes, so you can check which request it was.
val REQUEST_IMAGE_CAPTURE_SOURCE_1 = 1
val REQUEST_IMAGE_CAPTURE_SOURCE_2 = 2
val REQUEST_IMAGE_CAPTURE_SOURCE_3 = 3
//...
camRead1.setOnClickListener { dispatchTakePictureIntent(REQUEST_IMAGE_CAPTURE_SOURCE_1) }
camRead2.setOnClickListener { dispatchTakePictureIntent(REQUEST_IMAGE_CAPTURE_SOURCE_2) }
camRead3.setOnClickListener { dispatchTakePictureIntent(REQUEST_IMAGE_CAPTURE_SOURCE_3) }
//...
private fun dispatchTakePictureIntent(requestCode: Int) {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
try {
startActivityForResult(takePictureIntent, requestCode)
} catch (e: ActivityNotFoundException) {
// display error state to the user
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode != RESULT_OK) {
// possibly show message to user
return
}
val imageViewId = when (requestCode) {
REQUEST_IMAGE_CAPTURE_SOURCE_1 -> R.id.thumbRead1
REQUEST_IMAGE_CAPTURE_SOURCE_2 -> R.id.thumbRead2
REQUEST_IMAGE_CAPTURE_SOURCE_3 -> R.id.thumbRead3
}
val imageView = findViewById<ImageView>(imageViewId)
imageView.imageBitmap = data.extras.get("data") as Bitmap
}
By the way, if you want to get an ID for a view using the String like you were showing you were trying, you would do it like this:
val viewId = resources.getIdentifier("thumbRead$imgId", "id", packageName)
val imageView = findViewById<ImageView>(viewId)
You need to pass different request code for each call and pass it to the dispatchTakePictureIntent function. You do not need to get id by findviewbyid. You simply can add the image on the basis of the request code.
val REQUEST_IMAGE_CAPTURE_ONE = 1
val REQUEST_IMAGE_CAPTURE_TWO = 2
val REQUEST_IMAGE_CAPTURE_THREE = 3
private fun dispatchTakePictureIntent(requestCode: Int) {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
try {
startActivityForResult(takePictureIntent, requestCode)
} catch (e: ActivityNotFoundException) {
// display error state to the user
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
val imageBitmap = data.extras.get("data") as Bitmap
if (requestCode == REQUEST_IMAGE_CAPTURE_ONE ) {
thumbRead1.setImageBitmap(imageBitmap)
}else if (requestCode == REQUEST_IMAGE_CAPTURE_TWO ) {
thumbRead2.setImageBitmap(imageBitmap)
}else if (requestCode == REQUEST_IMAGE_CAPTURE_THREE ) {
thumbRead3.setImageBitmap(imageBitmap)
}
}
}

Method from OnActivityResult Fragment executed, but nothing happend in View

can you help me., ?
I am new in develop Android use kotlin, and still learning.,
this my code on Fragment.,
......
private fun takePhotoFromCamera() {
Dexter.withActivity(requireActivity())
.withPermissions(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
)
.withListener(object : MultiplePermissionsListener {
override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
// Here after all the permission are granted launch the CAMERA to capture an image.
if (report!!.areAllPermissionsGranted()) {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra("Document", 2)
startActivityForResult(intent, CAMERA)
}
}
override fun onPermissionRationaleShouldBeShown(
permissions: MutableList<PermissionRequest>?,
token: PermissionToken?,
) {
showRationalDialogForPermissions()
}
}).onSameThread()
.check()
}
private fun choosePhotoFromGallery() {
Dexter.withActivity(activity)
.withPermissions(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
.withListener(object : MultiplePermissionsListener {
override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
// Here after all the permission are granted launch the gallery to select and image.
if (report!!.areAllPermissionsGranted()) {
val galleryIntent = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
galleryIntent.putExtra("Document", 2)
startActivityForResult(galleryIntent, GALLERY)
}
}
override fun onPermissionRationaleShouldBeShown(
permissions: MutableList<PermissionRequest>?,
token: PermissionToken?,
) {
showRationalDialogForPermissions()
}
}).onSameThread()
.check()
}
and this onActivityResult from parent Activity for Fragment
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
for (fragment in supportFragmentManager.fragments) {
fragment.onActivityResult(requestCode, resultCode, data)
}
}
And this OnActivityResult from Fragment
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
if (requestCode == GALLERY) {
if (data != null) {
val contentURI = data.data
try {
// Here this is used to get an bitmap from URI
#Suppress("DEPRECATION")
val selectedImageBitmap =
MediaStore.Images.Media.getBitmap(requireActivity().contentResolver,
contentURI)
// TODO (Step 3 : Saving an image which is selected from GALLERY. And printed the path in logcat.)
// START
val saveImageToInternalStorage =
saveImageToInternalStorage(selectedImageBitmap)
Log.i("Saved Image : ", "Path :: $saveImageToInternalStorage")
// END
binding.btnNpwpCaptureAgain.visibility=View.VISIBLE
binding.ivPvNpwp.foreground.clearColorFilter()
binding.cvNpwp.visibility=View.GONE
binding.btnCaptureNpwp.visibility=View.GONE
binding.ivNpwpPreview.setImageBitmap(selectedImageBitmap) // Set the selected image from GALLERY to imageView.
} catch (e: IOException) {
e.printStackTrace()
Toast.makeText(requireActivity(), "Failed!", Toast.LENGTH_SHORT).show()
}
}
} else if (requestCode == CAMERA) {
val thumbnail: Bitmap = data!!.extras!!.get("data") as Bitmap // Bitmap from camera
// TODO (Step 4 : Saving an image which is selected from CAMERA. And printed the path in logcat.)
// START
val saveImageToInternalStorage =
saveImageToInternalStorage(thumbnail)
Log.i("Saved Image : ", "Path :: $saveImageToInternalStorage")
//binding.btnCaptureKtp.text = getString(R.string.regist_step_2_KTP_retake).toString()
// END
binding.btnNpwpCaptureAgain.visibility=View.VISIBLE
binding.ivPvNpwp.foreground.clearColorFilter()
binding.btnCaptureNpwp.visibility=View.GONE
binding.cvNpwp.visibility=View.GONE
binding.ivNpwpPreview.setImageBitmap(thumbnail) // Set to the imageView.
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("Cancelled", "Cancelled")
}
//
}
My Problem is why this block is executed, but nothing happend ??
....
binding.btnNpwpCaptureAgain.visibility=View.VISIBLE
binding.ivPvNpwp.foreground.clearColorFilter()
binding.btnCaptureNpwp.visibility=View.GONE
binding.cvNpwp.visibility=View.GONE
binding.ivNpwpPreview.setImageBitmap(thumbnail)
......
Thank you for respond my question.,
Try with putting another null check for "contentURI". Like :-
if(contentURI != null){
try {
// Here this is used to get an bitmap from URI
#Suppress("DEPRECATION")
val selectedImageBitmap =
MediaStore.Images.Media.getBitmap(requireActivity().contentResolver,
contentURI)
// TODO (Step 3 : Saving an image which is selected from GALLERY. And printed the path in logcat.)
// START
val saveImageToInternalStorage =
saveImageToInternalStorage(selectedImageBitmap)
Log.i("Saved Image : ", "Path :: $saveImageToInternalStorage")
// END
binding.btnNpwpCaptureAgain.visibility=View.VISIBLE
binding.ivPvNpwp.foreground.clearColorFilter()
binding.cvNpwp.visibility=View.GONE
binding.btnCaptureNpwp.visibility=View.GONE
binding.ivNpwpPreview.setImageBitmap(selectedImageBitmap) // Set the selected image from GALLERY to imageView.
} catch (e: IOException) {
e.printStackTrace()
Toast.makeText(requireActivity(), "Failed!", Toast.LENGTH_SHORT).show()
}
}
As onActivityResult() method is deprecated, its better to use registerForActivityResult(). Like below :
private val startForResultToLoadImage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
try {
val selectedImage: Uri? = result.data?.data
if (selectedImage != null){
// From Gallery
// Use uri to get the image
}else{
// From Camera code goes here.
// Get the bitmap directly from camera
val bitmap: Bitmap = result.data?.extras?.get("data") Bitmap
}
} catch (error: Exception) {
Log.d("log==>>", "Error : ${error.localizedMessage}")
}
}
}
For gallery call it like:
val intent = Intent (Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startForResultToLoadImage.launch(intent)
For camera call it like:
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.putExtra(MediaStore.EXTRA_OUTPUT, it)
startForResultToLoadImage.launch(intent)
I believe you should:
Print log at the start of the function with all of the parameters printed to always know how the code will branch. Something like Log.i("onActivityResult: ", "requestCode=" + requestCode + “, resultCode=” + resultCode + “, data=” + data);
Check your request code before you check result code since different requests may have different results.
You’re assuming the result would be either Activity.RESULT_CANCELED or Activity.RESULT_OK but the result code might be a custom result, so please add another else branch after you check Activity.RESULT_CANCELED to be sure you’re covering all results.
Don’t call Fragment.onActivityResult from Activity.onActivityResult if your activity inherits from AppCompatActivity. Activity automatically forward the result to fragments (it even allows request code duplication across fragments without mixing the fragments).
The structure of onActivityResult should be mainly:
if (requestCode == REQUEST_1) {
if (resultCode == RESULT_1) {
// Do your thing
} else if (resultCode == RESULT_2) {
// Do your thing
} else if (resultCode == RESULT_LAST) {
// Do your thing
} else {
// Important!! Expect the unexpected
}
} else if (requestCode == REQUEST_2) {
...
} else if (requestCode == REQUEST_LAST) {
...
}
I would use switch-case instead if-else but it’s you code style so I won’t judge :)

How can I set a request code under different conditions for my activity to bypass onActivityResult?

I have a program that allows me to store data(pictures and metadata with the taken picture) during the execution of a picture being taking with the android system camera activity... but I have code in place to make sure that the user enters data into a popup activity before the camera activity is displayed by using the OnActivityResult function(this way the user's photo has information that is stored as metadata in my firebase database). I was wondering If I can set a request code that wouldn't be equal to the REQUESTCODE2 so that under the condition that my back button is pressed(which will still result in the REQUESTCODE2 being returned for the com.example.myapplication.nameofphoto activity, which then will trigger takepic()) I can purposely make sure that the request code is faulty so that takepic() does not trigger and I don't store null data into my database.
for your information: nameofpersonvar , and nameofphotovar are both in a different class and is the information from the popup activity
private const val REQUESTCODE = 2
private const val REQUESTCODE2 = 3
fun take_pic(){
val takephotoIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takephotoIntent.resolveActivity(this.packageManager) != null) {
startActivityForResult(takephotoIntent, REQUESTCODE)
} else {
Toast.makeText(this, "Unable To access Camera... ", Toast.LENGTH_LONG)
.show()
}
}
photoButton.setOnClickListener {
val action3 = Intent(this , com.example.myapplication.nameofphoto::class.java)
startActivityForResult(action3, REQUESTCODE2 )
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (REQUESTCODE == requestCode && resultCode == Activity.RESULT_OK) {
//Compressing the bitmap(image) into a byte[] to match the input of the .putbytes method
val userimage = data?.extras?.get("data") as Bitmap
val byteoutput = ByteArrayOutputStream()
userimage.compress(Bitmap.CompressFormat.JPEG,100 , byteoutput)
val data = byteoutput.toByteArray()
//ref to the firebase "bucket" database
val storageinfo = FirebaseStorage.getInstance().getReference("/Images" )
//extra data that shows who the images belong to (users)
val metadatastoreage = storageMetadata {
setCustomMetadata("Name of person" , nameofpersonvar)
setCustomMetadata("Name of photo" , nameofphotovar)}
storageinfo.putBytes(data, metadatastoreage)
}else if (requestCode ==REQUESTCODE2) {
take_pic()
}
else {
super.onActivityResult(requestCode, resultCode, data)
}
}
Then why don't you send some result code different from the back press method of the current activity opened and check if the result is successful then take pick otherwise do something.
send this as result code from back press method. RESULT_CANCELED
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (REQUESTCODE == requestCode && resultCode == Activity.RESULT_OK) {
//Compressing the bitmap(image) into a byte[] to match the input of the .putbytes method
val userimage = data?.extras?.get("data") as Bitmap
val byteoutput = ByteArrayOutputStream()
userimage.compress(Bitmap.CompressFormat.JPEG,100 , byteoutput)
val data = byteoutput.toByteArray()
//ref to the firebase "bucket" database
val storageinfo = FirebaseStorage.getInstance().getReference("/Images" )
//extra data that shows who the images belong to (users)
val metadatastoreage = storageMetadata {
setCustomMetadata("Name of person" , nameofpersonvar)
setCustomMetadata("Name of photo" , nameofphotovar)}
storageinfo.putBytes(data, metadatastoreage)
return
}
if (requestCode ==REQUESTCODE2 && resultcode == Activity.RESULT_OK) {
take_pic()
} else {
//back pressed do something.
//finish etc
}
}
Edit: You can override the onBackPressed() in the popup activity and send some data using intent to the parent activity. for ex.
Intent resultIntent = new Intent();
// TODO Add extras or a data URI to this intent as appropriate.
resultIntent.putExtra("user_pic_click", "some data");
setResult(Activity.RESULT_OK, resultIntent);
finish();

Categories

Resources