Me estoy haciendo mailjava.io.FileNotFoundException incluso después de la adición de los permisos de usuario

Susnt:

Estoy creando un botón que, Fetch base de datos, crear el archivo de .xls en los documentos de la carpeta y enviarlo como un archivo adjunto en el correo electrónico o WhatsApp. Sin embargo, estoy consiguiendo error mailjava.io.FileNotFoundException incluso después de la adición de permisos para el archivo de manifiesto. Sé que es algo pequeño que me falta, pero no puedo averiguar.

  1. He intentado crear archivos en el directorio de caché interna, donde se crea el archivo correctamente pero no puede ser descabellada como archivo adjunto al correo electrónico o WhatsApp.
  2. No tengo ningún problema en que el archivo debe ser guardado, porque estoy eliminarlo de todas formas después de enviar como archivo adjunto.
  3. Email Intención, he jugado con Uri como Uri.parse ( "contenido: //", file.getAbsolutePath ()) file.toUri (); Uri uri = Uri.fromFile (archivo); Todos tienen los mismos resultados que muestran este error. clase padre ha definido todas las variables

        imbtnMail.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
              try {
    
                Cursor cursor = dbManager.fetch(DatabaseHelper.TICKET_TABLE);
    
                String filename = "Report-" + DateUtil.timeMilisToString(System.currentTimeMillis(), "ddMMyy");
                String xlsfile = filename + ".xlx";
                file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), xlsfile);
                Log.i("File written at:",file.getAbsolutePath());
    
                //file path
                WorkbookSettings wbSettings = new WorkbookSettings();
                wbSettings.setLocale(new Locale("en", "EN"));
                WritableWorkbook workbook;
                workbook = Workbook.createWorkbook(file, wbSettings);
                //Excel sheet name. 0 represents first sheet
                WritableSheet sheet = workbook.createSheet("Daily Report", 0);
    
                // column and row
                sheet.addCell(new Label(0, 0, "Pass Report"));
                sheet.addCell(new Label(1, 0, "User"));
    
                if (cursor.moveToFirst()) {
                    do {
                        String Rno = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TICKET_RECEIPT));
                        String vno = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TICKET_V_NO));
                        String vtype = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TICKET_V_TYPE));
                        String vin = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TICKET_V_IN_TIME));
                        String vout = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TICKET_V_OUT_TIME));
                        int i = cursor.getPosition() + 1;
                        sheet.addCell(new Label(0, i, Rno));
                        sheet.addCell(new Label(1, i, vno));
                        sheet.addCell(new Label(2, i, vtype));
                        sheet.addCell(new Label(3, i, vin));
                        sheet.addCell(new Label(4, i, vout));
                    } while (cursor.moveToNext());
                }
    
                //closing cursor
                cursor.close();
                workbook.write();
                workbook.close();
    
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("*/*");
                intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
                intent.putExtra(Intent.EXTRA_SUBJECT, "subject here");
                intent.putExtra(Intent.EXTRA_TEXT, "body text");
                if (!file.exists() || !file.canRead()) {
                    Toast.makeText(ViewLog.this, "Attachment Error", Toast.LENGTH_SHORT).show();
                    return;
                }
                Uri uri = Uri.fromFile(file);
    
                intent.putExtra(Intent.EXTRA_STREAM, uri);
                startActivityForResult(Intent.createChooser(intent, "Send email..."),ViewLog.REQUEST_WRITE_STORAGE);
            } catch (Exception e) {
                System.out.println("is exception raises during sending mail" + e);
            }
        }
    });
    

Y este es el error que yo estoy poniendo después de hacer clic en este botón

E / System.out: es aumentos de excepción durante el envío mailjava.io.FileNotFoundException: /storage/emulated/0/Documents/Report-020219.xlx (No existe el fichero o directorio)

manifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="mypackagename">
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:ignore="GoogleAppIndexingWarning">
    <activity android:name=".VehicleSetup"></activity>
    <activity android:name=".About" />
    <activity android:name=".Parked" />
    <activity android:name=".AppSetup" />
    <activity android:name=".ViewLog" />
    <activity android:name=".LoginActivity" />
    <activity android:name=".Main" />
    <activity android:name=".Splashscreen">
      <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Quiero que este archivo escrito en cualquier ubicación, pero debe ser tomado como archivo adjunto en cualquier cliente de correo electrónico o WhatsApp

Susnt:

Acabo de descubrir el error responsables de mailjava.io.FileNotFoundException como única instancia fue creada y no el archivo real.

Básicamente, hay dos errores responsables de esto.

  1. Declaré ejemplo del archivo (archivo) en la clase en sí (no en el método onClick). Desde que se declaró en una variable de clase, que arroja FileUriExposedException que de hecho expuesto el URI que cogió en el bloque catch.
  2. Yo estaba tratando de ir a buscar ese archivo desde el directorio de caché interna, que no está permitido en GMail 5.0 de acuerdo con este tema

Solución

  1. Declarar instancia archivo en el método onClick misma manera que URI no está expuesto.
  2. Crear archivo en ExternalSD porque es accesible mundo y aceptada por GMail 5.0
imbtnMail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    Cursor cursor = dbManager.fetch(DatabaseHelper.TICKET_TABLE);
                    File file = new File(Environment.getExternalStorageDirectory(),"Report-"+DateUtil.timeMilisToString(System.currentTimeMillis(),"hh-MM-yy")+".xls");
                    Toast.makeText(getApplicationContext(),"File saved",Toast.LENGTH_LONG).show();

                    WorkbookSettings wbSettings = new WorkbookSettings();
                    wbSettings.setLocale(new Locale("en", "EN"));
                    WritableWorkbook workbook;
                    workbook = Workbook.createWorkbook(file, wbSettings);
                    WritableSheet sheet = workbook.createSheet("Daily Report", 0);

                    // column and row
                    sheet.addCell(new Label(0, 0, "Pass Report"));
                    sheet.addCell(new Label(1, 0, "User"));

                    if (cursor.moveToFirst()) {
                        do {
                            String Rno = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TICKET_RECEIPT));
                            String vno = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TICKET_V_NO));
                            String vtype = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TICKET_V_TYPE));
                            String vin = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TICKET_V_IN_TIME));
                            String vout = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TICKET_V_OUT_TIME));
                            int i = cursor.getPosition() + 1;
                            sheet.addCell(new Label(0, i, Rno));
                            sheet.addCell(new Label(1, i, vno));
                            sheet.addCell(new Label(2, i, vtype));
                            sheet.addCell(new Label(3, i, vin));
                            sheet.addCell(new Label(4, i, vout));
                        } while (cursor.moveToNext());
                    }

                    //closing cursor
                    cursor.close();
                    workbook.write();
                    workbook.close();

                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    intent.putExtra(Intent.EXTRA_EMAIL, new String[] {"[email protected]"});
                    intent.putExtra(Intent.EXTRA_SUBJECT, "subject here");
                    intent.putExtra(Intent.EXTRA_TEXT, "body text");
                    if (!file.exists() || !file.canRead()) {
                        Toast.makeText(getApplicationContext(), "Attachment Error", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Uri uri = Uri.fromFile(file);
                    intent.putExtra(Intent.EXTRA_STREAM, uri);
                    startActivity(Intent.createChooser(intent, "Send email..."));
                }
                catch (Exception e){e.printStackTrace();}
            }
        });

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=219792&siteId=1
Recomendado
Clasificación