0

I am displaying my files in a recyclerview, the goal is to be able to send them in an email as an implicit intent when clicked, so the user does not have to do this manually by pulling them from the external storage.

However, when I attempt to do this my app crashes, with no error messages.. Here is my main activity that fetches the file path and attempts to send it, the code that does this specifically is in the sendAsMail and OnItemClick methods

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FileView extends AppCompatActivity {

    private RecyclerView fileRecyclerView;
    private RowAdapter fileAdapter;
    private RecyclerView.LayoutManager fileLayoutManager;
    private ArrayList<RowItem> rowItem;
    private List<File> fileList;
    private final String filePath = "PDF_files";
    private String fileData = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_view);
        File file = new File(getExternalFilesDir(filePath).toString());
        fileList = Arrays.asList(file.listFiles());
        createRows();
        buildRecyclerView();
    }

    public void createRows(){
        rowItem = new ArrayList<>();
        for (int i = 0; i < fileList.size(); i++) {
            rowItem.add(new RowItem(R.drawable.ic_book,(fileList.get(i).getName().replace("__", " ").replace('_','\n').replace('-','/').replace(".pdf",""))));
        }
    }

    public void removeItem(int position) {
        rowItem.remove(position);
        fileAdapter.notifyItemRemoved(position);
    }

    public void reListFiles(){
        File file = new File(getExternalFilesDir(filePath).toString());
        fileList = Arrays.asList(file.listFiles());
    }

    public void sendAsMail(String file) {

        Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
        shareIntent.setType("application/pdf");

        shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Sample Subject"); //set your subject
        shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Sample Text"); //set your message

        String filePath = file;
        File fileToShare = new File(filePath);
        Uri uri = Uri.fromFile(fileToShare);
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(shareIntent, "Share File"));
    }


    public void buildRecyclerView() {

        fileRecyclerView = findViewById(R.id.recyclerView);
        fileRecyclerView.setHasFixedSize(true);
        fileLayoutManager = new LinearLayoutManager(this);
        fileAdapter = new RowAdapter(rowItem);
        fileRecyclerView.setLayoutManager(fileLayoutManager);
        fileRecyclerView.setAdapter(fileAdapter);

        fileAdapter.setOnItemClickListener(new RowAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                fileData = fileList.get(position).toString();
            //    Toast.makeText(FileView.this,"Clicked: " + fileData , Toast.LENGTH_SHORT).show();
                sendAsMail(fileData);
            }

            @Override
            public void onDeleteClick(int position) {
                removeItem(position);

                File deletePath = fileList.get(position);
                deletePath.delete();
                if(deletePath.exists()){
                    getApplicationContext().deleteFile(deletePath.getName());
                }
                reListFiles();
            }

            @Override
            public void onMenuClick(int position) {
            }
        });
    }
}

EDITED with suggested solution

My sendAsMail method

   private void sendEmail(File attatchedFile, String name) {

        //File pdfFile = attatchedFile;
        File pdfFile = attatchedFile;
        Log.v("sendEmail STARTED: ","attatched file vaariable saved as File:  " + pdfFile);

        // Write data in your file
        Uri uri = FileProvider.getUriForFile(this, getPackageName(), pdfFile);

        Intent intent = ShareCompat.IntentBuilder.from(this)
                .setStream(uri) // uri from FileProvider
                .getIntent()
                .setAction(Intent.ACTION_VIEW) //Change if needed
                .setDataAndType(uri, "pdf/*")
                .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        startActivity(intent);
    }

Calling the method in the onclick

        fileAdapter.setOnItemClickListener(new RowAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                String name = fileList.get(position).getName();
                fileData = fileList.get(position);
                //Log.d("LOG: ","fileData: " + fileData + " name: " + name);
                sendEmail(fileData, name);
            }

The following variables I am passing to the sendEmail method

FileData: /storage/emulated/0/Android/data/com.loopbreakr.firstpdf/files/PDF_files/file__name_2021-01-28_16:20:14.pdf

name: file__name_2021-01-28_16:20:14.pdf

EDIT - My log on crash

2021-01-28 17:08:11.904 19378-19378/com.loopbreakr.firstpdf V/STARTING METHOD W/:: fileData: /storage/emulated/0/Android/data/com.loopbreakr.firstpdf/files/PDF_files/file__name_2021-01-28_16:20:14.pdf name: file__name_2021-01-28_16:20:14.pdf
2021-01-28 17:08:11.904 19378-19378/com.loopbreakr.firstpdf V/sendEmail STARTED:: attatched file vaariable saved as File:  /storage/emulated/0/Android/data/com.loopbreakr.firstpdf/files/PDF_files/file__name_2021-01-28_16:20:14.pdf
2021-01-28 17:08:11.906 19378-19378/com.loopbreakr.firstpdf D/AndroidRuntime: Shutting down VM
2021-01-28 17:08:11.907 19378-19378/com.loopbreakr.firstpdf E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.loopbreakr.firstpdf, PID: 19378
    java.lang.IllegalArgumentException: Couldn't find meta-data for provider with authority com.loopbreakr.firstpdf
        at androidx.core.content.FileProvider.parsePathStrategy(FileProvider.java:606)
        at androidx.core.content.FileProvider.getPathStrategy(FileProvider.java:579)
        at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:417)
        at com.loopbreakr.firstpdf.FileView.sendEmail(FileView.java:71)
        at com.loopbreakr.firstpdf.FileView.access$200(FileView.java:25)
        at com.loopbreakr.firstpdf.FileView$1.onItemClick(FileView.java:99)
        at com.loopbreakr.firstpdf.RowAdapter$RowViewHolder.lambda$new$0$RowAdapter$RowViewHolder(RowAdapter.java:51)
        at com.loopbreakr.firstpdf.-$$Lambda$RowAdapter$RowViewHolder$D8MO8iiQsge5Oqk6qgHk3jkm7ew.onClick(Unknown Source:4)
        at android.view.View.performClick(View.java:7448)
        at android.view.View.performClickInternal(View.java:7425)
        at android.view.View.access$3600(View.java:810)
        at android.view.View$PerformClick.run(View.java:28305)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
MKer
  • 83
  • 2
  • 8
  • If your app crashes then there was an exception you did not catch. Look in the Logcat for which one. – blackapps Jan 28 '21 at 09:21
  • 1
    `Uri.fromFile(fileToShare);` That will only work on below Android N/7 devices. Now you have to use FileProvider.getUriFromFile(). – blackapps Jan 28 '21 at 09:24
  • And add a flag GRAND_READ_URI_PERMISSION. – blackapps Jan 28 '21 at 09:25
  • You're right, I think the issue lies with this. I tried it out though and I think I am not properly declaring it. Can you please post an example of how you would do it in my case? – MKer Jan 28 '21 at 11:20
  • Just post your new code. – blackapps Jan 28 '21 at 11:23
  • I just did, please take a look and and advise how to do it correctly if you have the time – MKer Jan 28 '21 at 19:59
  • `fileList.get(position).getName();` That does not tell me what name you use. Please use a hard coded name. The same for the next path statement. We need to know what you do. – blackapps Jan 28 '21 at 20:20
  • And why dont you call your function like sendEmail(name, fileData); – blackapps Jan 28 '21 at 20:21
  • `filePath.mkdir();` Better: if(!file.exists()) if(!mkdirs()) { Toast( ... Sorry could not create directory ); return;} – blackapps Jan 28 '21 at 20:29
  • Does your code work? – blackapps Jan 28 '21 at 20:30
  • Thank you for following up. I logged the result of the variables I'm getting, I can;t use hard coded string as the application I posted needs to get the filename on item click based on the position of the RecyclerView. The logged variables I am returning on item click are as follows fileData: /storage/emulated/0/Android/data/com.loopbreakr.firstpdf/files/PDF_files/file__name_2021-01-28_16:20:14.pdf name: file__name_2021-01-28_16:20:14.pdf – MKer Jan 28 '21 at 21:21
  • Also used your suggestion to pass both variables, edited code to reflect this but unfortunately still crash. This is API30/Android 11 btw, does it have something to do with permissions? – MKer Jan 28 '21 at 21:32
  • What kind of crash do you have? The logcat will tell the exception that lets your app crash. Of course you can hardcode the values you just told. – blackapps Jan 28 '21 at 21:55
  • `File pdfFile = new File(attatchedFile.getPath(), name);` No. `File pdfFile = attatchedFile;` – blackapps Jan 28 '21 at 21:59
  • Sure thing, I edited my post to include that and I made the change you suggested too – MKer Jan 28 '21 at 22:10
  • Did you define FileProvider: https://developer.android.com/reference/androidx/core/content/FileProvider ? – Honza Musil Jan 28 '21 at 22:14

0 Answers0