I am trying to take a picture using the camera and display the same. While the same works fine in the emulator it does not work in my samsung j5 prime device
Here is my code:
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { cameraIntent ->
cameraIntent.resolveActivity(packageManager)?.also {
val pictureFile : File? = try {
getPictureFile()
} catch (ex: IOException) {
Toast.makeText(this,
"Photo file can't be created, please try again",
Toast.LENGTH_SHORT).show()
null
}
pictureFile ?.also {
photoURI = FileProvider.getUriForFile(
this,
"$packageName.fileprovider",
it
)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(cameraIntent, REQUEST_CAMERA)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val imgFile = File(pictureFilePath)
Log.d("MyMessage",data.toString())
if (data != null) {
if (imgFile.exists())
{
previewbox.setImageBitmap(setScaledBitmap())
prescripPreview.visibility = View.VISIBLE
filepath = photoURI
}
}
}
When I use an emulator the log returns intent { }
But in the device the log returns null. What is the issue here?
Related
I am new to Android development, and im making simple aplication that capture image then save. I can capture the image and show into imageview, but unfortunately i cannot save into gallery.
i tryed many ways but cannot save. this is original code to take and show.
// EDITED //
I add function to save file, but still not working
class TomarFotos : AppCompatActivity() {
lateinit var photoPath: String
val REQUEST_IMAGE_CAPTURE = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tomar_fotos)
val foto = findViewById<Button>(R.id.tomarfotos)
foto.setOnClickListener{
tomarFoto()
}
}
fun tomarFoto() {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if(intent.resolveActivity(packageManager) != null){
var photoFile: File? = null
try{
photoFile = createImageFile()
}catch (e: IOException){}
if(photoFile != null){
val photoUri = FileProvider.getUriForFile(
this,
"com.example.android.fileprovider",
photoFile
)
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
startActivityForResult(intent,REQUEST_IMAGE_CAPTURE)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val fotoTomada = findViewById<ImageView>(R.id.fotopreview)
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
fotoTomada.rotation = 90f
fotoTomada.setImageURI(Uri.parse(photoPath))
}
}
private fun createImageFile(): File? {
val fileName = "foto"
val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val image = File.createTempFile(
fileName,
".jpg",
storageDir
)
photoPath = image.absolutePath
return image
}
}
i try developer.android.com already but didnt work
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val fotoTomada = findViewById<ImageView>(R.id.fotopreview)
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
val imageBitmap = data?.extras?.get("data") as Bitmap
fotoTomada.setImageBitmap(imageBitmap)
saveImage(imageBitmap)
}
}
Call this function to save image to gallery
private fun saveImage(bitmap: Bitmap) {
var outStream: FileOutputStream? = null
// Write to SD Card
try {
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "AppName/")
dir.mkdirs()
val fileName = "IMG_${System.currentTimeMillis()}"
val outFile = File(dir, fileName)
outStream = FileOutputStream(outFile)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)
outStream.flush()
outStream.close()
Toast.makeText(this#MainActivity, "Image Saved Successfully", Toast.LENGTH_LONG).show()
} catch (e: FileNotFoundException) {
Log.d("TAG", "saveImage: ${e.message}")
} catch (e: IOException) {
Log.d("TAG", "saveImage: ${e.message}")
}
}
I'trying to open camera with video and photo.This code working correctly but in onActivityResult can't check file type. data.data is null
Here is a code
private fun openCamera() {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val takeVideoIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
val chooserIntent = Intent(Intent.ACTION_CHOOSER)
val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT)
val intentArray = arrayOf(takePictureIntent, takeVideoIntent)
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent)
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Choose an action")
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray)
startActivityForResult(chooserIntent, CAMERA_STATUS_CODE)
}
onActivityResult code snippet
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val selectedMediaUri = data?.data
if (resultCode == RESULT_OK) {
when (requestCode) {
GALERY_STATUS_CODE -> {
}
CAMERA_STATUS_CODE -> {
val path = data!!.data!!.path
if (path!!.contains("/video/")) {
} else if (path.contains("/images/")) {
}
}
}
}
}
what's a wrong in my code?!
Thanks
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
}
I want to send a photo from the gallery and the camera as a file to the server and I have used the library canhub but in the activityResult the data is null.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
GALLERY_REQUEST_CODE -> {
if (resultCode == Activity.RESULT_OK) {
data?.data?.let { uri ->
launchImageCrop(uri)
}
}
}
CAMERA_REQUEST_CODE -> {
if (resultCode == Activity.RESULT_OK) {
data!!.data?.let { uri ->
launchImageCrop(uri)
}
}
}
CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE -> {
val result = CropImage.getActivityResult(data)
if (resultCode == Activity.RESULT_OK && requestCode == GALLERY_REQUEST_CODE) {
val file = File(Environment.getExternalStorageDirectory(), "read.me")
val uri = Uri.fromFile(file)
val auxFile = File(uri.path)
viewModel.getUserCardInfo(auxFile)
} else {
(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
// val error = CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE
// toast(error)
}
if (resultCode == Activity.RESULT_OK && requestCode == CAMERA_REQUEST_CODE) {
val photo: Bitmap = result!!.bitmap
val mFile = context?.convertToFile(photo)
if (mFile != null) {
viewModel.getUserCardInfo(mFile)
}
}else{
CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE
}
}
}
}
and
private fun launchImageCrop(uri: Uri) {
CropImage.activity(uri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1920, 1080)
.setCropShape(CropImageView.CropShape.RECTANGLE)
.start(requireContext(),this);
}
and add manifest
android:requestLegacyExternalStorage="true"
Hi i faced a similar issue , please try this sometimes the problem is google are not allowing to use Environment.getExternalStorageDirectory()
This is the new way
ContextWrapper cw = new ContextWrapper(mContext);
File directory = cw.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File file = new File(directory, "name_of_file");
Also please don't use android:requestLegacyExternalStorage="true", google might reject your app in playstore
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?) {