Sígvardr Ólavrsson Sígvardr Ólavrsson - 3 months ago 23
Android Question

Android - Attach image to E-mail

I am working on a feedback feature within my app, the user is supposed to select an image from the gallery and type his message and press send, on send button click the code is supposed to to get the text from the box (figure below) and attach it to the email intent and send the whole thing, everything seems to work just fine until I get the "can't attach empty file" toast message, this is how far I got in the code

String rating = String.valueOf(RateBar.getRating());
String subject = Feedback.getText().toString();
String FileLocation = FilePathPreview.getText().toString();
String to ="EngNor.supp@gmail.com";
String message = UserInput.getText().toString();
String body = "Rating : "+rating+" out of 5"+
"\n "+message;
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, body);
email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:/"+FileLocation));

//need this to prompts email client only
email.setType("message/rfc822");

startActivity(Intent.createChooser(email, "Choose an Email client :"));





public void grabImg(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String PathP = selectedImage.getPath().toString();
FilePathPreview.setText(PathP);
}
}


Feedback activity

Answer

Create a globale Uri variable then save the uri in onActivityResult()

Uri uri = null;

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
        if(resultCode == RESULT_OK){
            Uri selectedImage = imageReturnedIntent.getData();
            uri  = selectedImage; // here set the uri 
            String PathP = selectedImage.getPath().toString();
            FilePathPreview.setText(PathP);
        }
}

then pass the same uri variable to

        //....
        email.putExtra(Intent.EXTRA_STREAM, uri);
        //....
        //need this to prompts email client only
        email.setType("message/rfc822");

        startActivity(Intent.createChooser(email, "Choose an Email client :"));

Update: Add this flag if you still cant share

email.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

Comments