Skip to content Skip to sidebar Skip to footer

How To Send Saved Csv File Via Email Or Upload With Google Drive In 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: Str

Solution 1:

Create an xml file in res/xml/provider_paths.xml

<?xml version="1.0" encoding="utf-8"?><pathsxmlns: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-pathname="scale"path="."/><!--
    another example:  Environment.getExternalStorageDirectory() + File.separator + "temps" + "myFile.pdf"
     --><external-pathname="myFile"path="temps"/></paths>

add provider in your application tag in manifest

<!--android:name="android.support.v4.content.FileProvider"--><providerandroid:name="androidx.core.content.FileProvider"android:authorities="your.application.package.fileprovider"android:grantUriPermissions="true"android:exported="false"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/provider_paths" /></provider>

Finally change your code to this:

publicstaticvoidsendEmailWithAttachment(Context context) {
    String filename="/scale.csv";
    Filefilelocation=newFile(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
    //Uri path = Uri.fromFile(filelocation);Uripath= FileProvider.getUriForFile(context, "your.application.package.fileprovider", filelocation);
    IntentemailIntent=newIntent(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

Post a Comment for "How To Send Saved Csv File Via Email Or Upload With Google Drive In Android?"