Search code examples
javaandroidsendfile

Try to send a csv file but the permission fails


I'm trying to send a file (Intent.ACTION_SEND) but when I use for example gmail, the permission fail, and gmail notify me the permission of the attached file don't permit send it. Here is my code:

private void LoadSendFile() {

    String temp = new String();
    File tempFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Datos" + ext);

    try {
        FileOutputStream fos = new FileOutputStream(tempFile);

        for (ActivityMat data : matriculas) {
            if (!data.getViajesConductor().isEmpty()) {
                for (String date : data.getViajesConductor()) {
                    temp += data.getName() + ": " + date + "\n";
                    fos.write(temp.getBytes());
                    Log.e("Write File: ", temp);
                }
            }
        }

        fos.close();

    } catch (FileNotFoundException e){
        Log.e("Creando fichero: ", e.getMessage(), e);
        Toast toast = Toast.makeText(MainActivity.this, "File not found ...", Toast.LENGTH_SHORT);
        toast.show();
        return;

    } catch (IOException e) {
        Log.e("Escribiendo fichero: ", e.getMessage(), e);
        Toast toast = Toast.makeText(MainActivity.this, "Can not build the file ...", Toast.LENGTH_SHORT);
        toast.show();
        return;
    }

    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
    sendIntent.setType("application/csv");
    startActivity(sendIntent);
}

Thanks in advance!!!

(Excuse my language, I'm not English)

UPDATE: The code had been updated. Now I have permission, but gmail notify me that it can't send an empty file, but I know (because I write a log message when I write in the file (Datos.csv)) that I write in the file. Any idea?? Here is the log (I saw is a problem of permission):

E/Creando fichero:: /storage/emulated/0/Datos.csv: open failed: EACCES (Permission denied)
                java.io.FileNotFoundException: /storage/emulated/0/Datos.csv: open failed: EACCES (Permission denied)
 ....  //here the "at" statement

Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)

Solution

  • getFilesDir() is private internal memory for your app. The email app has no acces to it.

    Try another location like getExternalStorageDirectory() or getExternalFilesDir().

    Moreover you need to request WRITE_EXTERNAL_STORAGE permission in manifest file.

    And if compiling for Android 6 and above request at runtime permission from the user for that.