This is my data class :-
data class User(val imagepic: Int)
Passing value to recycler view :-
users.add(User(R.drawable.splash_bc))
users.add(User(R.drawable.image))
users.add(User(R.drawable.splash_bc))
users.add(User(R.drawable.share))
users.add(User(R.drawable.splash_bc))
users.add(User(R.drawable.image))
this is my share function :-
Here I am passing user as Input
fun shareString(user: User) {
var image_path: String
val file : File = File(user)
val uri = Uri.fromFile(file)
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image/*"
intent.putExtra(Intent.EXTRA_STREAM, uri)
startActivity(itemView.context, Intent.createChooser(intent,"Share to :"),null)
}
I am not able to share image. getting casting error everytime.
Please help on this
I don't think you are parsing the drawable file right way.
basically drawable is an int value in "User", You can't parse that to uri.
check this one for reference
This is working for me :
fun shareString(context: Context,user: User) {
val b = BitmapFactory.decodeResource(context.resources, user.mImage)
val share = Intent(Intent.ACTION_SEND)
share.type = "image/jpeg"
val path = MediaStore.Images.Media.insertImage(context.contentResolver, b, "Title", null)
val imageUri: Uri = Uri.parse(path)
share.putExtra(Intent.EXTRA_STREAM, imageUri)
startActivity(context,Intent.createChooser(share, "Select"),null)
}
I have pass context value from mainActivity.
Related
I have two activities and I am trying to pass image by using Serializable way. How to do this? Is it possible to pass image by using Serializable way? Any ideas please.
val resultImage = findViewById<ImageView>(R.id.resultImage)
val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
resultImage.setImageURI(uri)
}
val galleryBtn = findViewById<Button>(R.id.galleryBtn)
val nextBtn = findViewById<Button>(R.id.nextBtn)
galleryBtn.setOnClickListener {
getContent.launch("image/*")
}
nextBtn.setOnClickListener {
val takeImage = resultImage.setImageURI(Uri)
val person = Person ()
Intent(this,SecoendActivity::class.java).also {
it.putExtra("EXTRA_PERSON",person)
startActivity(it)
}
}
In kotlin class file:
data class Person(
val imageUrl: Bitmap
): Serializable
My second activity:
val imageView = findViewById<ImageView>(R.id.imageView)
val person = intent.getSerializableExtra("EXTRA_PERSON")as Person
It is not recommended to use Serializable to pass images between activities, as it can cause memory and performance issues. Instead, you can use the Intent.putExtra method to pass the image's URI to the other activity, and then use the ContentResolver to retrieve the image in the second activity.
// In the first activity
val imageUri = Uri.parse("content://...")
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("image_uri", imageUri)
startActivity(intent)
// In the second activity
val imageUri = intent.getParcelableExtra<Uri>("image_uri")
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
I'm trying to retrieve URI from gallery and camera in one place (as record in Room database), therefore i need to standardize the access between them. I get it done for the camera by create a file and then retrieve its URI. The URI looks like this:
// first URI
content://media/external_primary/images/media/45
It works and i can retrieve the image based on that URI after reopening the app.
Here is the code for camera
private val launcherIntentCamera = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == RESULT_OK) {
val bitmap = result?.data?.extras?.get("data") as Bitmap
val uri = savePhotoToExternalStorage(
requireActivity().contentResolver,
UUID.randomUUID().toString(),
bitmap
)
uri?.let {
viewModel.updateProfilePic(it.toString())
}
}
}
private fun startTakePhoto() {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
launcherIntentCamera.launch(intent)
}
And then i try for gallery intent and what i receive is this:
// second URI
content://com.android.providers.media.documents/document/image%3A44
Based on what i observe, this URI is temporary. And when i try to retrieve it after reopening the app, it doesnt work.
This is my code
private val launcherIntentGallery = registerForActivityResult(
ActivityResultContracts.GetContent()
) { uri ->
viewModel.updateProfilePic(uri.toString())
}
private fun startGallery() {
requireActivity().intent.type = "image/*"
launcherIntentGallery.launch("image/*")
}
Is there any solution to convert the second URI to the format of first URI so i could retrieve the image when reopening the app?
I want to share a list of images to WhatsApp, however, if I share a single image the code works fine and the image is shared to whatsapp but when sharing multiple images whatsapp shows file format not supported toast message
here is my code
val cachePath = File(requireContext().cacheDir, "images")
cachePath.mkdirs()
val uriList = arrayListOf<Uri>()
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image/*"
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
GlobalScope.launch {
shareClicked.images.forEach {
val loader = ImageLoader(requireContext())
val request = ImageRequest.Builder(requireContext())
.data(
it.image
)
.allowHardware(false)
.build()
val result = (loader.execute(request) as SuccessResult).drawable
val bitmap = (result as BitmapDrawable).bitmap
val UUID = UUID.randomUUID()
val stream =
FileOutputStream("$cachePath/${UUID}.jpg")
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
val newFile = File(cachePath, "$UUID.jpg")
val contentUri: Uri = FileProvider.getUriForFile(
requireContext(),
"provider",
newFile
)
uriList.add(contentUri)
}
Im doing an app and i want to share photo just i saved to phone to another apps like instagram twitter.Im not able to do it and i cant see where the mistake is.Here is my code
`private fun getScreenshot(currentPage: Int){
QuickShot.of(requireActivity().findViewById<ConstraintLayout(currentPage))
.setResultListener(this)
.enableLogging()
.setFilename("screen")
.setPath("Spotibud")
.toJPG()
.save()
}
override fun onQuickShotSuccess(path: String?) {
Log.d(TAG, "onQuickShotSuccess: $path")
shareOnInstagram(path!!)
}
override fun onQuickShotFailed(path: String?, errorMsg: String?) {
Log.d(TAG, "onQuickShotFailed: $errorMsg")
}
private fun shareOnInstagram(path: String){
val stickerAssetUri: Uri = Uri.parse(path)
val intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_STREAM,stickerAssetUri)
type = "image/*"
}
startActivity(intent)
}`
and my log when app saves image
2021-02-18 17:28:08.750 16355-16355/com.example.contestifyfirsttry D/Home Fragment: onQuickShotSuccess: /Pictures/Spotibud/screen.jpg
also is there any code how i can see error.try catch not worked
now i found the solution this isnt best practice but im sure it makes you to see what you should do
private fun shareOnInstagram(path: String){
var file : File = File("/storage/emulated/0/Pictures/Spotibud/screen.jpg")
if (file.exists()){
Log.d(TAG, "shareOnInstagram: file exists")
val stickerAssetUri: Uri = Uri.fromFile(file)
val sourceApplication = "com.example.contestifyfirsttry"
val intent = Intent("com.instagram.share.ADD_TO_STORY")
intent.putExtra("source_application", sourceApplication)
intent.type = "image/*"
intent.putExtra("interactive_asset_uri", stickerAssetUri)
intent.putExtra("top_background_color", "#33FF33")
intent.putExtra("bottom_background_color", "#FF00FF")
val activity: Activity? = activity
activity!!.grantUriPermission(
"com.instagram.android", stickerAssetUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
)
if (activity!!.packageManager.resolveActivity(intent, 0) != null) {
activity!!.startActivityForResult(intent, 0)
}
}else{
Log.d(TAG, "shareOnInstagram: file dont exists")
}
}
I have an activity from which I launch the gallery, select an image, and want to display the selected image in another activity. I have referred to the following solution and implemented the same.
How to get Image URI from Gallery?
Though I am able to pass the URI to the next activity, I cannot see anything on the image view. Any help as to where I am going wrong, appreciated.
btn_launch_gallery.setOnClickListener {
val requestCode = 0
val launchGalleryIntent = Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(launchGalleryIntent, requestCode)
}
My OnActivityResult looks like this, basically implemented the same as given in the example cited above.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode === 0 && resultCode === Activity.RESULT_OK ) {
val selectedImage: Uri? = data?.data
val picturePath = getRealPathFromURI(
selectedImage,
this
)
val intent = Intent(this, LogFoodDetail::class.java)
intent.putExtra("image_from_gallery", picturePath)
try {
startActivity(intent)
}
catch (e: Exception)
{
e.printStackTrace()
Log.e("Error",e.printStackTrace().toString())
}
}
}
fun getRealPathFromURI(contentURI: Uri?, context: Activity): String? {
val projection =
arrayOf(MediaStore.Images.Media.DATA)
val cursor = context.managedQuery(
contentURI, projection, null,
null, null
)
?: return null
val column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
return if (cursor.moveToFirst()) {
// cursor.close();
cursor.getString(column_index)
} else null
// cursor.close();
}
In my next activity, I getting the intent like this and passing the URI to ImageView. However, I cannot see the image. I get the following error - W/System.err: java.io.FileNotFoundException: No content provider: /storage/emulated/0/DCIM/Camera/***.jpg
val resId = intent.getStringExtra("image_from_gallery")
val imgThumbnail: ImageView = findViewById(R.id.food_thumbnail)
try{
val imageStream: InputStream? = contentResolver.openInputStream(Uri.parse(resId))
val bitmap = BitmapFactory.decodeStream(imageStream)
imgThumbnail.setImageBitmap(bitmap)
}
catch (e: Exception)
{
e.printStackTrace()
}
I see the following image in the next activity:
UPDATE:
As commented by #blackapps in his answer passing the URI as a string to the next activity on an intent.putExtra() and resolving the URI in the subsequent activity solved it, the updated code in OnActivityResult() is,
...
val selectedImage: Uri? = data?.data
val intent = Intent(this, LogFoodDetail::class.java)
intent.putExtra("image_from_gallery",
selectedImage.toString())
startActivity(intent)
Dont convert a nice uri to a file system path.
Uri uri = data.getData();
Pass the obtained uri directly to the next activity.
And there you can use it for
imageView.setImageUri(uri);
Instead of the uri you can also pass the uri as string with uri.toString().
You can directly load an local image Uri using:
imgThumbnail.setImageUri(yourUri);
Instead of sending the string path to the activity, you should send the raw uri and then set it directly to the imageView.