Cannot find saved CSV or TXT file on Android [duplicate] - android

I have a simple logging app that collects data into three arraylists, which I want saved to a CSV file and then shared to Google Drive, email, etc.
Here is how I save the data:
StringBuilder data = new StringBuilder();
data.append("Timestamp,Mass,Change in Mass\n");
for(int i = 0; i < mass_list.size(); i++){
data.append(String.valueOf(timestamp_list.get(i))+ ","+String.valueOf(mass_list.get(i))+","+String.valueOf(mass_roc_list.get(i))+"\n");
}
FileOutputStream out = openFileOutput("scale.csv", Context.MODE_APPEND );
out.write(data.toString().getBytes());
out.close();
This just combined my ArrayLists into a string and saves the data into csv file with name scale.
Here is how I am attempting to share it:
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[{"email#gmail.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Scale Data");
emailIntent.putExtra(Intent.EXTRA_TEXT, "This is the body");
emailIntent.putExtra(Intent.EXTRA_STREAM, Environment.getExternalStorageDirectory() + "/scale.csv");
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
When I try this in an email, there is no attachment, just the body. When I try with Google Drive, just the body gets saved to a text file. I am not sure what I am doing wrong, but it probably has something to do with file locations. Maybe I am unable to find the file that I saved in?
I would appreciate any assistance and am ready to provide clarification upon request.
EDIT Using feedback
I tried one of the proposed solutions. This is what my code looks like now:
StringBuilder data = new StringBuilder();
data.append("Timestamp,Mass,Change in Mass\n");
for(int i = 0; i < mass_list.size(); i++){
data.append(String.valueOf(timestamp_list.get(i))+ ","+String.valueOf(mass_list.get(i))+","+String.valueOf(mass_roc_list.get(i))+"\n");
}
try {
//saving data to a file
FileOutputStream out = openFileOutput("scale.csv", Context.MODE_APPEND);
out.write(data.toString().getBytes());
out.close();
Context context = getApplicationContext();
String filename="/scale.csv";
File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
Uri path = FileProvider.getUriForFile(context, "com.example.scaleapp.fileprovider", filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// set the type to 'email'
emailIntent.setType("vnd.android.cursor.dir/email");
String to[] = {"email.com"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Scale Data");
emailIntent.putExtra(Intent.EXTRA_TEXT, "This is the body");
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
//this line is where an exception occurs and "Error" is displayed on my phone
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
infoView.setText("Something worked!");
}
catch(Exception e){
e.printStackTrace();
infoView.setText("Error");
}
Everything compiles and runs normally. However, when I upload to Drive, it says "unable to upload" and when I send an email, it says "unable to attach an empty file".

Create an xml file in res/xml/provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!--
name is the file name
path is the root of external storage, it means here: Environment.getExternalStorageDirectory()
-->
<external-path name="scale" path="."/>
<!--
another example: Environment.getExternalStorageDirectory() + File.separator + "temps" + "myFile.pdf"
-->
<external-path name="myFile" path="temps"/>
</paths>
add provider in your application tag in manifest
<!--android:name="android.support.v4.content.FileProvider"-->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="your.application.package.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
Finally change your code to this:
public static void sendEmailWithAttachment(Context context) {
String filename="/scale.csv";
File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
//Uri path = Uri.fromFile(filelocation);
Uri path = FileProvider.getUriForFile(context, "your.application.package.fileprovider", filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// set the type to 'email'
emailIntent .setType("vnd.android.cursor.dir/email");
String to[] = {"email#gmail.com"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Scale Data");
emailIntent.putExtra(Intent.EXTRA_TEXT, "This is the body");
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// the attachment
emailIntent .putExtra(Intent.EXTRA_STREAM, path);
context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
Some tips about defining file path from android docs
<files-path name="name" path="path" />
Represents Context.getFilesDir()
<cache-path name="name" path="path" />
Represents getCacheDir()
<external-path name="name" path="path" />
Represents Environment.getExternalStorageDirectory().
<external-cache-path name="name" path="path" />
Represents Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)
<external-media-path name="name" path="path" />
Represents Context.getExternalCacheDir().
Read more from docs

Related

Android send email with multiple attachment using file provider

Android App Problems sending an email with multiple attachments using File Provider.
I was using intent.putExtra(Intent.EXTRA_STREAM, Uri.parse( "file://"+csvFilePath)); and I have no issues sending single attachment file. Then I need to send multiple attachments. I have a problem to get it working.
In my AndroidManifest.xml I specify the provider with the following code :
<provider
android:name="android.support.v4.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>
Here is my xml/provider_paths
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="myfiles"
path="Android/data/com.example.abc/files/Documents"/>
</paths>
Send email code and files path are :
csvFilePath : /storage/emulated/0/Android/data/com.example.abc/files/Documents/Test123.csv
xyzFilePath : /storage/emulated/0/Android/data/com.example.abc/files/Documents/xyz123.txt
//attach multiple file
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("text/plain");
ArrayList<Uri> uris = new ArrayList<Uri>();
//uris.add(Uri.fromFile(new File(csvFilePath)));
//uris.add(Uri.fromFile(new File(xyzFilePath)));
// using file provider
File csvFile = new File(csvFilePath);
File xyzFile = new File(xyzFilePath);
uris.add(FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", csvFile ));
uris.add(FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", xyzFile ));
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
intent.setData(Uri.parse("mailto:" + abc#xyz.com));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
Exception raises during sending mailandroid.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.SEND_MULTIPLE dat=mailto:xxx.xxxxxxxx#xxxxx.xxx flg=0x10000001 clip={null U:content://com.example.abc.provider/myfiles/Test123.csv ...} (has extras) }
Found a solution with the following code :
xml/provider_paths
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
File baseDir = new File(Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOCUMENTS), "ABC");
if (!baseDir.exists()) {
baseDir.mkdirs();
}
Log.i("Debug", "baseDir " + baseDir.toString());
File f1 = new File(baseDir, "File1.txt");
writeToFile(f1, "This is file 1 contents 888888888");
Log.i("Debug", "f1 path" + f1.getAbsolutePath());
File f2 = new File(baseDir, "File2.txt");
writeToFile(f2, "This is file 2 contents 123456");
Log.i("Debug", "f2 path" + f2.getAbsolutePath());
String f1path = f1.toString();
String f2path = f2.toString();
string EXTRA_RECIPIENT = "janedoe#abc.com";
String message = "Test message 12345678 this is a test. ";
sendMail(f1path, f2path, message, EXTRA_RECIPIENT);
private void sendMail(String f1path, String f2path, String message, String mailTo) {
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Test multiple attachments");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{mailTo});
File f1new = new File(f1path);
File f2new = new File(f2path);
ArrayList<Uri> uris = new ArrayList<Uri>();
uris.add(FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", f1new ));
uris.add(FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", f2new ));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_TEXT, message);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(intent);
}
The gmail or mail sending apps may be disabled in your mobile. Kindly check the apps are enabled.
This ActivityNotFoundException occurs mainly when there is no application to handle the intent.
Then I need to send multiple attachments. I have a problem to get it
working.
Example for multiple attachments:
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_SUBJECT, "Test multiple");
intent.putExtra(Intent.EXTRA_TEXT, "multiple attachments");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient_address});
ArrayList<Uri> uris = new ArrayList<Uri>();
uris.add(Uri.fromFile(new File("/path/to/first/file")));
uris.add(Uri.fromFile(new File("/path/to/second/file")));
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
Finish with a call to startActivity() passing intent.

Sharing Audio and Text With Single Intent

Hi It would help me greatly If anyone could please help me out. I have been trying to find a solution to Share my Audio File with a Text using Intent. I am just trying to share it on Whatsapp alone. It would be greatly appreciated if any of you could spare time out to help me out of this problem. When I run my code only the sound is shared. No text.
This is my code:
public void buttonClick(View v) {
try {
String a = copyFiletoExternalStorage(R.raw.accio, "accio.mp3");
String shareBody = "Here is the share content body";
Intent shareMedia = new Intent(Intent.ACTION_SEND);
//set WhatsApp application.
shareMedia.setPackage("com.whatsapp");
shareMedia.setType("*/*");
//set path of media file in ExternalStorage.
shareMedia.putExtra(Intent.EXTRA_STREAM, Uri.parse(a));
shareMedia.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
shareMedia.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(shareMedia, "Compartiendo archivo."));
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Whatsapp no se encuentra instalado", Toast.LENGTH_LONG).show();
}
}
I want the user to share the sound and the text in just one intent.
first you need to add provider_paths.xml
see this video to add file provider
my file provider
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
then add this line to AndroidManifest.xml
<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>
then use this code to share your voice and text
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "some text ... ");
sendIntent.setType("text/plain");
if (hasReadExternalStoragePermission()) {
Uri uriImage = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".provider", new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "voice.wav"));
sendIntent.putExtra(Intent.EXTRA_STREAM, uriImage);
sendIntent.setType("audio/*");
}
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(sendIntent, "share"));
I hope it has been helpful
Try to use Intent.ACTION_SEND_MULTIPLE instead of Intent.ACTION_SEND
Intent shareMedia = new Intent(Intent.ACTION_SEND_MULTIPLE);
//set WhatsApp application.
shareMedia.setPackage("com.whatsapp");
shareMedia.setType("*/*");
String[] extraMimeTypes = {"audio/*", "image/*"};
shareIntent.putExtra(Intent.EXTRA_MIME_TYPES, extraMimeTypes);
shareIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
shareMedia.putExtra(Intent.EXTRA_STREAM, Uri.parse(a));
shareMedia.putExtra(Intent.EXTRA_SUBJECT, "Subject Here");
shareMedia.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(shareMedia, "Compartiendo archivo."));

Error: Cannot attach empty file in GMAIL app using File provider

I am trying to attach a pdf file in gmail app. I have read this and this (applied solution) I am trying as;
public static void attachFile(Context ctx) {
String TAG = "Attach";
File documentsPath = new File(ctx.getFilesDir(), "documents");
Log.i(TAG,"documentsAbsolutePath Output");
Log.i(TAG, documentsPath.getAbsolutePath().toString());
File file = new File(documentsPath, "sample.pdf");
if ( file.exists() ) {
Toast.makeText(ctx, "Exits", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(ctx, "Not Exist", Toast.LENGTH_LONG).show();
}
Log.i(TAG,"file Output");
Log.i(TAG, file.toString());
Log.i(TAG, String.valueOf(file.length()));
Uri uri = FileProvider.getUriForFile(ctx, "com.example.fyp_awais.attachfiletest2.fileprovider", file);
Log.i(TAG,"URI Output");
Log.i(TAG,uri.toString());
Intent intent = ShareCompat.IntentBuilder.from((Activity) ctx)
.setType("application/pdf")
.setStream(uri)
.setChooserTitle("Choose bar")
.createChooserIntent()
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
ctx.startActivity(intent);
}
Outputs
documentsAbsolutePath Output
/data/data/com.example.fyp_awais.attachfiletest2/files/documents
file Output
/data/data/com.example.fyp_awais.attachfiletest2/files/documents/sample.pdf
0
URI Output
content://com.example.fyp_awais.attachfiletest2.fileprovider/pdf_folder/sample.pdf
Menifest
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.fyp_awais.attachfiletest2.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepath" />
</provider>
FilePath.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="pdf_folder" path="documents/"/>
</paths>
</PreferenceScreen
A pdf file is saved in Galaxy Core Prime\Phone\documents. (file size: 53.7KB)
But it gives
Cannot attach empty file.
I am confused with folder-name in this line <files-path name="pdf_folder" path="documents/"/>. The file is in the \Phone\documents. Then why folder name?
Edit 1
Tried to replace setType(application/pdf) with setType("message/rfc822") But did not work. Any help?
Send the file in URI format like this:
Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("application/image");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
ArrayList<Uri> uris = new ArrayList<>();
//convert from paths to Android friendly Parcelable Uri's
uris.add(frontImageUri);
uris.add(backImageUri);
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
if it's ok To send Zip then try this way
String fileNameStor_zip = Environment.getExternalStorageDirectory() + "/" + fileName + ".zip";
String[] path = { your 1st pdf File Path, your 2nd pdf File Path};
Compress compress = new Compress(path, fileNameStor_zip);
compress.zip();
URI = Uri.parse("file://" + fileNameStor_zip);
Provide your Gmail Intent
intent.putExtra(Intent.EXTRA_STREAM, URI);
Uri contentUri = FileProvider.getUriForFile(this, "com.mydomain.fileprovider", newFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
i.setData(contentUri);
String filename="my_file.vcf";
File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// set the type to 'email'
emailIntent .setType("vnd.android.cursor.dir/email");
String to[] = {"asd#gmail.com"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
emailIntent .putExtra(Intent.EXTRA_STREAM, path);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(emailIntent , "Send email..."));
You have to grant the permission to access storage for gmail.
In case it helps- here's what I do in an app debug function with a few files, it shouldn't really be any different.
I do copy/export them into a user-public folder first before attaching them, and make them world readable.
if (verifyStoragePermissions(c)) {
final Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"recipient#email.address"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");
//build up message
ArrayList<Uri> uris = new ArrayList<>();
StringBuilder content = new StringBuilder();
content.append(
String.format(
c.getString(R.string.message_log_upload_email_body) +
"\n\nmodelDesc:%s \n\nmanuf:%s \n\naId: %s,\n\nhIid: %s,\n\nfbId: %s.",
Build.MODEL, Build.MANUFACTURER, getSomeVar1(), getSomeVar2(), getSomeVar3())
);
content.append("\n\nMy logged in account id is: ").append(getAccountId(c)).append(".");
content.append("\n\nHere's an overview of my attachments:\n");
for (String s : addresses) {
File f = new File(s);
//noinspection ResultOfMethodCallIgnored
f.setReadable(true, false);
Uri add = Uri.fromFile(f);
//add attachment manifest
content.append(String.format(Locale.UK, "|-> %s (%.3f kb)\n", f.getName(), (float) f.length() / 1024));
uris.add(add);
}
//attach the things
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
//set content/message
intent.putExtra(Intent.EXTRA_TEXT, content.toString());
c.startActivity(intent);
}
}
addresses is a String[] param to that function. I build it up by making the functions I use to export the files return arrays of strings of the addresses of the files they've exported - as I initially store the files in my app's private storage

share image with URL android share intent

I need to know if it is possible to share an image using only its url with a share intent. Here is my code.
Intent imageIntent = new Intent(Intent.ACTION_SEND);
Uri imageUri = Uri.parse("http://eofdreams.com/data_images/dreams/face/face-03.jpg");
imageIntent.setType("image/*");
imageIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(imageIntent);
So far its not working and I haven't found any helpful answers online. I would like to do this using the share intent and without downloading the image.
You can share image using share intent, but you've to decode image to a localized Bitmap
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hey view/download this image");
String path = Images.Media.insertImage(getContentResolver(), loadedImage, "", null);
Uri screenshotUri = Uri.parse(path);
intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
intent.setType("image/*");
startActivity(Intent.createChooser(intent, "Share image via..."));
loadedImage is the loaded bitmap from http://eofdreams.com/data_images/dreams/face/face-03.jpg
See here HERE
final ImageView imgview= (ImageView)findViewById(R.id.feedImage1);
Uri bmpUri = getLocalBitmapUri(imgview);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
// ...sharing failed, handle error
}
then add this to your activity :
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
I've tried several methods, however non of them worked for me and the parts of the operations were unclear, so here is what I use for sharing image or video type content in case having the absolute path of the data.
In android manifest.xml add the following lines:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
//Other codes
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
//Other codes
</application>
In the resource directory res, make a new folder called xml. Place a new file into it with the same name you used in the manifest.xml at the meta-data part, in this case provider_paths.xml:
android:resource="#xml/provider_paths"
Place the following in it:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_files"
path="." />
<root-path
name="external_files"
path="/storage/"/>
</paths>
In the activity you wish to use the share function, place the following code, where path is a string variable containing the absolute path of the content, and "com.example.fileprovider", the author value of Fileprovider is based on one of the line of the fresh xml file created above like this:
android:authorities="com.example.fileprovider"
File file = new File(path);
//Checking if the file exists
if(file.exists()) {
//Creating the Uri for the file using the provider we just created
Uri contentUri =
FileProvider.getUriForFile(Gallery.this,"com.example.fileprovider", file);
//Creating the share intent
Intent S = new Intent(Intent.ACTION_SEND);
//Allowing different types to be shared
S.setType("*/*");
S.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//Providing the uri to the intent
S.putExtra(Intent.EXTRA_STREAM, contentUri);
//Starting the intent, can choose from apps which are listening for the
//content type
startActivity(Intent.createChooser(S, "Share content using"));
}
else{
Toast.makeText(getApplicationContext(),path + " does not
exist",Toast.LENGTH_SHORT).show();
}
With this it is easy to share content from the device with the path of it.
The authorities and resource values are crucial in manifest.xml. One can change them of course, but then make sure to modify them at all occurances.
Resources:
Android Share Intent Image Sharing not working Except WhatsApp
https://www.geeksforgeeks.org/how-to-share-image-from-url-with-intent-in-android/
https://developer.android.com/training/sharing/send
convert url to string format
Intent imageIntent = new Intent(Intent.ACTION_SEND);
Uri imageUri = Uri.parse("http://eofdreams.com/data_images/dreams/face/face-03.jpg");
imageIntent.setType("image/*");
imageIntent.putExtra(Intent.EXTRA_STREAM, String.valueOf(imageUri));
startActivity(imageIntent);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,"http://eofdreams.com/data_images/dreams/face/face-03.jpg");
startActivity(Intent.createChooser(intent, "Share Image"));

Android send mail with attachment from string

I have a HTML string which I want to attach to mail as a file. I could save this string to a file and attach it but I want to do it without saving it to a file. I think it should be possible but I don't know how to do it. This is my code:
String html = "<html><body><b><bold</b><u>underline</u></body></html>";
Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(html));
// this is where I want to create attachment
intent.putExtra(Intent.EXTRA_STREAM, Html.fromHtml(html));
startActivity(Intent.createChooser(intent, "Send Email"));
How can I attach string as a file to mail?
This code saves you from adding a manifest uses permission to read from external sd card. It creates a temp in files directory on your app private directory then creates the file with the contents of your string and allows read permission so that it can be accessed.
String phoneDesc = "content string to send as attachment";
FileOutputStream fos = null;
try {
fos = openFileOutput("tempFile", Context.MODE_WORLD_READABLE);
fos.write(phoneDesc.getBytes(),0,phoneDesc.getBytes().length);
fos.flush();
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
if (fos != null)try {fos.close();} catch (IOException ie) {ie.printStackTrace();}
}
File tempFBDataFile = new File(getFilesDir(),"tempFile");
Intent emailClient = new Intent(Intent.ACTION_SENDTO, Uri.parse("someone#somewhere.com"));
emailClient.putExtra(Intent.EXTRA_SUBJECT, "Sample Subject";
emailClient.putExtra(Intent.EXTRA_TEXT, "Sample mail body content");
emailClient.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFBDataFile));//attachment
Intent emailChooser = Intent.createChooser(emailClient, "select email client");
startActivity(emailChooser);
This should be called whenever you dont need the file anymore.
File tempData = new File(getFilesDir(),"tempFile");
if (tempData.exists()) {
tempData.delete();
}
String pathname= Environment.getExternalStorageDirectory().getAbsolutePath();
String filename="/MyFiles/mysdfile.txt";
File file=new File(pathname, filename);
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_SUBJECT, "Title");
i.putExtra(Intent.EXTRA_TEXT, "Content");
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
i.setType("text/plain");
startActivity(Intent.createChooser(i, "Your email id"));
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("png/image");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {
"mail--id" });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
Uri uri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "/saved_images/MyImage.png"));
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
emailIntent.setType("text/plain");
startActivity(emailIntent);
and don't forget to add this below permission in manifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" /

Categories

Resources