Я получаю mailjava.io.FileNotFoundException даже после добавления пользовательских разрешений - PullRequest
0 голосов
/ 02 февраля 2019

Я создаю кнопку, которая, Fetch database, создает файл .xls в папке с документами и отправляет его в виде вложения в электронное письмо или WhatsApp.Однако я получаю сообщение об ошибке mailjava.io.FileNotFoundException даже после добавления разрешений в файл манифеста.Я знаю, что-то маленькое, что мне не хватает, но не могу понять.

  1. Я попытался создать файл в каталоге внутреннего кэша, где файл успешно создан, но не может быть извлечен как приложение к электронной почте или WhatsApp.
  2. У меня нет проблем с сохранением файла, потому что я все равно его удаляю после отправки в виде вложения.
  3. В Email Intent я поиграл с Urias Uri.parse ("content: //", file.getAbsolutePath ()) file.toUri ();Uri uri = Uri.fromFile (файл);Все имеют одинаковые результаты, показывая эту ошибку.Родительский класс имеет все определенные переменные

        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@example.com"});
                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);
            }
        }
    });
    

И это ошибка, которую я улавливаю после нажатия этой кнопки

I / System.out: isВозникает исключение во время отправки mailjava.io.FileNotFoundException: /storage/emulated/0/Documents/Report-020219.xlx (Нет такого файла или каталога)

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>

Я хочу, чтобы этот файл был записан в любом месте, но его следует воспринимать как вложение в любом почтовом клиенте или WhatsApp

1 Ответ

0 голосов
/ 03 февраля 2019

Я только что обнаружил ошибку, ответственную за mailjava.io.FileNotFoundException, поскольку был создан только экземпляр, а не фактический файл.

По сути, за это были две ошибки.

  1. Я объявил экземпляр файла (файл) в самом классе (не в методе onClick).Поскольку он был объявлен в переменной класса, он генерирует исключение FileUriExposedException, которое действительно выявляет URI, захваченный в блоке catch.
  2. Я пытался извлечь этот файл из внутреннего кэшированного каталога, что запрещено в GMail 5.0 в соответствии с эта проблема

Решение

  1. Объявите экземпляр файла в самом методе onClick, чтобы URI не отображался.
  2. Создайте файл в ExternalSD, потому что он доступен всему миру и принят 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@example.com"});
                    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();}
            }
        });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...