Issue
private fun showImagePicDialog() { val options = arrayOf("Take Photo", "Take Video", "Choose Photo", "Choose Video") val builder = AlertDialog.Builder(requireContext()) builder.setTitle("Pick Post From...") builder.setItems(options) { dialog, which -> when (which) { 0 -> takePhoto() 1 -> takeVideo() 2 -> choosePhoto() 3 -> chooseVideo() } } builder.create().show() }
private fun takePhoto() {
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, 1000)
}
private fun takeVideo() {
val cameraIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
startActivityForResult(cameraIntent, 1001)
}
private fun choosePhoto() {
val cameraIntent = Intent(Intent.ACTION_GET_CONTENT)
cameraIntent.type = "image/*"
if (cameraIntent.resolveActivity(requireActivity().packageManager) != null) {
startActivityForResult(cameraIntent, 1002)
}
}
private fun chooseVideo() {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "video/*"
startActivityForResult(intent, 1003)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
1000 -> {
if (resultCode == Activity.RESULT_OK) {
takePhotoBitmap = data?.extras?.get("data") as? Bitmap
if (takePhotoBitmap != null) {
binding.sImgUploadPost.setImageBitmap(takePhotoBitmap)
}
} else {
requireContext().showToast("Photo capture was canceled or failed")
}
}
1001 -> {
if (resultCode == Activity.RESULT_OK) {
takeVideoURI = data?.data
if (takeVideoURI != null) {
// Handle the captured video URI
// For example, you can display it in a VideoView
binding.sVidUploadPost.setVideoURI(takeVideoURI)
binding.sVidUploadPost.start()
}
} else {
// Video recording was canceled or failed
requireContext().showToast("Video recording was canceled or failed")
}
}
1002 -> {
if (resultCode == Activity.RESULT_OK && data != null && data.data != null) {
choosePhotoURI = data?.data
if (choosePhotoURI != null) {
Glide.with(this).load(choosePhotoURI).centerCrop()
.transition(DrawableTransitionOptions.withCrossFade())
.into(binding.sImgUploadPost)
}
} else {
requireContext().showToast("Photo selection was canceled or failed")
}
}
1003 -> {
if (resultCode == Activity.RESULT_OK && data != null && data.data != null) {
chooseVideoURI = data?.data
if (chooseVideoURI != null) {
// Handle the selected video URI
// For example, you can display it in a VideoView
binding.sVidUploadPost.setVideoURI(chooseVideoURI)
binding.sVidUploadPost.start()
}
} else {
requireContext().showToast("Video selection was canceled or failed")
}
}
}
}
startActivityForResult and super.onActivityResult(requestCode, resultCode, data) is deprecated can please solve the issue ?
Solution
private val takePictureLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
// The photo was captured and saved successfully
// Display the captured image in your ImageView
appCompatImageView.setImageURI(Uri.parse(currentPhotoPath))
} else {
// Photo capture failed or was canceled
Toast.makeText(this, "Photo capture failed or was canceled", Toast.LENGTH_SHORT)
.show()
}
}
private val pickImageLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK && result.data != null) {
val selectedImageUri: Uri? = result.data?.data
if (selectedImageUri != null) {
// Set the selected image to the ImageView
appCompatImageView.setImageURI(selectedImageUri)
} else {
Toast.makeText(this, "Failed to load image", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "Image selection canceled", Toast.LENGTH_SHORT).show()
}
}
private val takeVideoLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
// Video recording was successful
val videoUri = result.data?.data
if (videoUri != null) {
setVideoToVideoView(videoUri)
}
} else {
// Video recording failed or was canceled
Toast.makeText(this, "Video recording failed or was canceled", Toast.LENGTH_SHORT)
.show()
}
}
private val pickVideoLauncher =
registerForActivityResult(ActivityResultContracts.GetContent()) { videoUri ->
if (videoUri != null) {
// Set the selected video to the VideoView
appCompatVideoView.setVideoURI(videoUri)
appCompatVideoView.start()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
takePicture = findViewById(R.id.btnTakePicture)
appCompatImageView = findViewById(R.id.appCompatImageView)
choosePicture = findViewById(R.id.btnChoosePicture)
takeVideo = findViewById(R.id.btnTakeVideo)
appCompatVideoView = findViewById(R.id.appCompatVideoView)
btnChooseVideo = findViewById(R.id.btnChooseVideo)
takePicture.setOnClickListener {
if (!hasPermissions(this, *REQUIRED_PERMISSIONS)) {
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, ALL_PERMISSIONS)
} else {
Toast.makeText(this, "All Permissions Granted", Toast.LENGTH_SHORT).show()
Handler(Looper.getMainLooper()).postDelayed({ startCamera() }, 1000)
}
}
choosePicture.setOnClickListener {
val galleryIntent =
Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
pickImageLauncher.launch(galleryIntent)
}
takeVideo.setOnClickListener {
if (!hasPermissions(this, *REQUIRED_PERMISSIONS)) {
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, ALL_PERMISSIONS)
} else {
Toast.makeText(this, "All Permissions Granted", Toast.LENGTH_SHORT).show()
startVideoRecording()
}
}
btnChooseVideo.setOnClickListener {
pickVideoLauncher.launch("video/*")
}
}
private fun startVideoRecording() {
if (!isRecording) {
val videoFile = createTempVideoFile()
videoUri = FileProvider.getUriForFile(
this, "com.example.makecameraapplication.provider", videoFile
)
val videoIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
videoIntent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri)
takeVideoLauncher.launch(videoIntent)
isRecording = true
} else {
stopVideoRecording()
}
}
private fun stopVideoRecording() {
isRecording = false
Toast.makeText(this, "Video recording stopped", Toast.LENGTH_SHORT).show()
}
private fun createTempVideoFile(): File {
val timeStamp: String = System.currentTimeMillis().toString()
val storageDir: File? =
getExternalFilesDir(Environment.DIRECTORY_MOVIES) // Store in Movies directory
return File.createTempFile(
"VIDEO_${timeStamp}_", ".mp4", storageDir
).apply {
currentVideoPath = absolutePath
}
}
private fun setVideoToVideoView(videoUri: Uri) {
appCompatVideoView.setVideoURI(Uri.parse(currentVideoPath))
appCompatVideoView.start()
}
private fun hasPermissions(context: Context, vararg permissions: String): Boolean =
permissions.all {
ActivityCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}
private fun createTempImageFile(): File {
val timeStamp: String = System.currentTimeMillis().toString()
val storageDir: File? = getExternalFilesDir(null)
return File.createTempFile(
"JPEG_${timeStamp}_", ".jpg", storageDir
).apply {
currentPhotoPath = absolutePath
}
}
private fun startCamera() {
val imageFile = createTempImageFile()
val photoURI: Uri = FileProvider.getUriForFile(
this, "com.example.makecameraapplication.provider", imageFile
)
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
takePictureLauncher.launch(cameraIntent)
}
private fun finishActivity() {
Toast.makeText(
this, "You must grant all required permissions to continue", Toast.LENGTH_SHORT
).show()/* finish()*/
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>, grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
ALL_PERMISSIONS -> {
if (grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
startCamera()
} else {
finishActivity()
}
}
}
}
companion object {
const val ALL_PERMISSIONS = 10
private val REQUIRED_PERMISSIONS = mutableListOf(
android.Manifest.permission.CAMERA,
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
).apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
add(android.Manifest.permission.READ_EXTERNAL_STORAGE)
}
}.toTypedArray()
}
Answered By - Shubham Sahu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.