android exporting to csv and sending as email attachment

Thanks for everyone who tried to help..After taking a full day I have send an email from my app with attachment..This is the working code..

String columnString =   "\"PersonName\",\"Gender\",\"Street1\",\"postOffice\",\"Age\"";
String dataString   =   "\"" + currentUser.userName +"\",\"" + currentUser.gender + "\",\"" + currentUser.street1 + "\",\"" + currentUser.postOFfice.toString()+ "\",\"" + currentUser.age.toString() + "\"";
String combinedString = columnString + "\n" + dataString;

File file   = null;
File root   = Environment.getExternalStorageDirectory();
if (root.canWrite()){
    File dir    =   new File (root.getAbsolutePath() + "/PersonData");
     dir.mkdirs();
     file   =   new File(dir, "Data.csv");
     FileOutputStream out   =   null;
    try {
        out = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            out.write(combinedString.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Uri u1  =   null;
u1  =   Uri.fromFile(file);

Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Person Details");
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/html");
startActivity(sendIntent);

Also If you have mounted your phone SDCard in the machine , this code wont work. Only one can access SDCard at one time. So in that case unmount your SDCard from computer and try..Thanks to the guy who answered here..Also make sure you have bought permission to write to external Storage in your manifest file…

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Hope it helps someone…Thanks for everyone who tried to help..

Leave a Comment