Share Image of image view with intent in Kotlin - android

I have an option in my app that share image to whatsapp,facebook etc. For share image through intent, i want specific image from image view on which share button is clicked.
I have the following code that does not work.it share an empty file to whatsapp.
val shareBtn = findViewById<TextView>(R.id.share_btn)
val postImage = findViewById<ImageView>(R.id.post_image)
val path:String?=postImage.tag.toString()
val file= File(path)
shareBtn.setOnClickListener {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image"
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file))
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(Intent.createChooser(intent, "Share Image"))

First to store image of ImageView , you need to convert to Bitmap
val bitMap : Bitmap =imageview.getDrawingCache();
now store this image to file
val bos : ByteArrayOutputStream = ByteArrayOutputStream();
bitMap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
val file : File = File(Environment.getExternalStorageDirectory() + File.separator + "your_file.jpg");
try {
file.createNewFile();
val fos : FileOutputStream = FileOutputStream(file);
fos.write(bos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
now create an intent by specifying type 'image/jpeg'
and setting extra stream and path of the file that is to be shared
val intent= new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/your_file.jpg"));
And start Activity by creating chooser
startActivity(Intent.createChooser(intent, "Share Image"));

a great way for share image file ( Kotlin ) :
first create a folder named xml in the res folder and create a new XML Resource File named provider_paths.xml and put the below code inside it :
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path
name="files"
path="."/>
<external-path
name="external_files"
path="."/>
</paths>
now go to the manifests folder and open the AndroidManifest.xml and then put the below code inside the <application> tag :
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>
now you put the below code in the setOnLongClickListener :
button.setOnLongClickListener {
try {
val file = File("pathOfFile")
if(file.exists()) {
val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
val intent = Intent(Intent.ACTION_SEND)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setType("image/*")
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent)
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
toast("Error")
}
}

Related

how to share an video from one app to another using file Provider?

I am trying to share an video from one app to another, but show me an error that "failed to find configure root/data/data/app_name/cache/videos/external files". I can't understand why it's not passing the uri to another app.
can anyone help me to solve this problem
here is file provider path
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="videos/"/>
</paths>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.myapp.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths" />
</provider>
here is my code
File video = null;
shareVideos(video);
private void shareVideos(File video) {
Uri uri = getVideoToShare(video);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("videos/mp4");
context.startActivity(Intent.createChooser(intent, "Share Via"));
}
private Uri getVideoToShare(File video) {
File imagefolder = new File(context.getCacheDir(), "videos");
Uri uri = null;
try {
imagefolder.mkdirs();
File file = new File(imagefolder, "external_files");
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.flush();
outputStream.close();
uri = FileProvider.getUriForFile(context, "com.myapp.fileprovider", file);
} catch (Exception e) {
Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_LONG).show();
}
return uri;
}
File imagefolder = new File(context.getCacheDir(), "videos");
You are storing your file in getCacheDir(). That requires a <cache-path> element in the FileProvider XML metadata resource. That is not what you have. You have:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="videos/"/>
</paths>
Change that to:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path name="external_files" path="videos/"/>
</paths>

Two file providers in android app image fileprovider not working

I am sharing the app with the file provider and I want to share the image from the bitmap.
I have two file providers number one is for share apk, number two for share image. apk file provider works good but the image share file provider not sharing images. if I share an image to WhatsApp, Gmail it says file format does not support it.
fileprovider.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-cache-path
name="apk"
path="/"/>
</paths>
provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-cache-path name="img" path="my_images/"/>
</paths>
imagesharefrombitmap.kt
imgBtnShare.setOnClickListener {
shareImage()
loadingDialoglordshiva.startDialog()
}
}
private fun shareImage() {
val bitmapShare = getBitmapFromView(relLayout)
val filename = "${System.currentTimeMillis()}.jpg"
val cachePath = File(externalCacheDir.toString() + "/my_images")
cachePath.mkdirs()
//create a png file
//create png file
val file = File(cachePath, filename)
val fileOutputStream: FileOutputStream
try {
fileOutputStream = FileOutputStream(file)
bitmapShare.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)
fileOutputStream.flush()
fileOutputStream.close()
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
val myImageFileUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider_paths",file)
//create a intent
//create a intent
val intent = Intent(Intent.ACTION_SEND)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.putExtra(Intent.EXTRA_STREAM, myImageFileUri)
intent.type = "image/jpg"
startActivity(Intent.createChooser(intent, "Share with"))
loadingDialoglordshiva.dismissDialog()
}
Manifest_file_only_provider_showed
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.lordshiva.myapplication.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/fileprovider"
/>
</provider>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.lordshiva.myapplication.provider_paths"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
if i run this share intent is opening. but share to WhatsApp,Gmail or something its says file format is not supported . help me I don't know how to solve this.
I am solved by share bitmap image directly to intent.

Kotlin - CSV file sharing request contains no data

for my app i'm attempting to create a csv file and share it via email/google drive.
however when i go to share the csv file, im am presented with the following "toast" . The code is located within a fragment.
upload was unsuccessful request contained no data
the following is my current code:
val HEADER = "ID, Pa, m/s, Actual L/s, Design Pa, Design L/s, Design %"
var fileName = "file://" + Environment.getExternalStorageDirectory() + "/Folder" + "/" + "mycsv.csv"
println(" Debug: pressed successfully!")
var path = activity!!.getExternalFilesDir(null) //get file directory for this package
//(Android/data/.../files | ... is your app package)
println(" Debug: path successfully!")
//create fileOut object
var fileOut = File(path, "mycsv.csv")
println(" Debug: file successfully!")
//delete any file object with path and filename that already exists
fileOut.delete()
println(" Debug: deleted successfully!")
//create a new file
fileOut.createNewFile()
println(" Debug: file created successfully!")
//append the header and a newline
fileOut.writeText(HEADER)
fileOut.writeText("\n")
// trying to append some data into csv file
println(" Debug: csv written successfully!")
println("Debug:$fileOut")
val sendIntent = Intent(Intent.ACTION_SEND)
sendIntent.putExtra(Intent.EXTRA_STREAM, fileName)
sendIntent.type = "text/csv"
startActivity(Intent.createChooser(sendIntent, "Share File"))
println(" Debug: sent page open successfully!")
i have tried following similar questions asked on this site, however none of them were able to help as they were not in kotlin or i was unable to interpret it for my example. The attempt i have in this code is the closest i have gotten.
i have also tried:
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(FileName))
as it was a suggested answer for Kotlin Android create and share CSV file
Would Anyone have any ideas on how to fix this?
i got it to work by first adding the following code into the androidManifest.xml
with in the section.
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.YOUR_PACKAGE_NAME.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
after this create an xml file in res>xml>provider_paths*
inside the provider_paths.xml aded the following code
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path
name="files"
path="."/>
<external-path
name="external_files"
path="."/>
</paths>
finally to create the CSV file the code below was used inside the onClickListener.
val csv_header = "ID, Pa, m/s, Actual L/s, DesignPa, Design L/s, Design %"
var filename = "export.csv"
var path = context!!.filesDir.absolutePath//get file directory for this package
//(Android/data/.../files | ... is your app package)
//create fileOut object
var fileOut = File(path, filename)
//delete any file object with path and filename that already exists
fileOut.delete()
//create a new file
fileOut.createNewFile()
//append the header and a newline
fileOut.appendText(csv_header)
fileOut.appendText("\n")
// trying to append some data into csv file
fileOut.appendText("$123")
fileOut.appendText(",")
fileOut.appendText("456")
println("debug: Write CSV successfully!")
if(fileOut.exists())
try {
val uri = FileProvider.getUriForFile(context!!, BuildConfig.APPLICATION_ID + ".provider", fileOut)
val intent = Intent(Intent.ACTION_SEND)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.type = "text/csv"
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
startActivity(Intent.createChooser(intent, "Share File"))
println(" Debug1: sent page open successfully!")
}catch (e: java.lang.Exception) {
e.printStackTrace()
println("debug: failed")
}

Don't attach file and send by email

I define FileProvider in manifest:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="root"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepaths"/>
</provider>
and write paths :
<files-path path="files/" name="files_name" />
I put file "1.txt" in "root"/files/1.txt
Created intent for send file by email:
val intentToSendToBd = Intent(Intent.ACTION_SEND)
val file = File(context.filesDir,"files/1.txt")
val ur = FileProvider.getUriForFile(context, "root", file )
intentToSendToBd.setType("text/plain")
intentToSendToBd.putExtra(Intent.EXTRA_STREAM, ur)
intentToSendToBd.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intentToSendToBd.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
And finally I get "couldn't attach file" in EmailApp.
I am using this code to share mp3 file using send_imtent
val sdCard = Environment.getExternalStorageDirectory()
val directory = File(sdCard.absolutePath + "/Demo Mobile/VoiceMail")
val f = File(directory, sharingFileName + ".mp3") //or any other format supported
**val uri = Uri.parse("file://" + f.absolutePath)**
val share = Intent(Intent.ACTION_SEND)
share.putExtra(Intent.EXTRA_STREAM, uri)
share.setType("audio/mp3")
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(Intent.createChooser(share, "Share Voicemail File"))
Thanks, Happy Coding...

Gallery opens and closes right after, when trying to read a file from internal Storage

Im using this method to save a image to my files folder in the app internal storage.
public static String saveToInternalStorage(Context ctx,Bitmap bitmapImage){
Date date = new Date();
File mypath = new File(ctx.getFilesDir(), "ATM_"+date.getTime()+".jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return mypath.getAbsolutePath();
}
In another option of the app i want to open the image in the android gallery and i try to do so with this code
Intent intent = new Intent();
// set flag to give temporary permission to external app to use your FileProvider
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// generate URI, I defined authority as the application ID in the Manifest, the last param is file I want to open
File file = new File(path);
if(file.exists() && file.isFile()) {
Uri uri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID, file);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(intent, 1);
}
I also have this declared on my manifest
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths"/>
</provider>
And my file_provider_paths looks like this
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="files" path="/"/>
What happens is that when i press the button to open the image on the gallery , i see the application picker for that file type , and when i choose gallery it opens and closes right after.
Question 1: Why is this happening?
Question 2: How to i open the gallery to show all of the images on the "files" folder from internal storage?

Categories

Resources