Android assest folder image attachment to email failed - android

I'm trying to send a mail attaching assest folder image to the mail, mail is sent successfully, but when i checked it there was no image attached to the mail,
this is my code,
Uri uri = Uri.fromFile(new File("file:///android_asset/Hat_5.png"));
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_EMAIL , new String[] { "some#gmail.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "New Order");
intent.putExtra(Intent.EXTRA_TEXT , "Order Id :" +imageId);
intent.putExtra(Intent.EXTRA_STREAM , uri);
startActivity(Intent.createChooser(intent, "Send mail..."));
permission,
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

You can only attach files from the SDCARD.
You'll need to copy the image to the SDCARD and change the URI the the file's path on the sdcard.
You could delete if afterwards.

You can do this if you want
String FILENAME = "avatar.png";
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
Log.v("","FileNotFoundException: "+e1.getMessage());
}
try {
InputStream inputStream = getAssets().open("avatar.jpg");
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
fos.write(buf,0,len);
fos.close();
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
Log.v("","IOException: "+e1.getMessage());
}
// Get the file from internal storage
String filePath = getApplicationContext().getFilesDir().getAbsolutePath();//returns current directory.
File file = new File(filePath, FILENAME);
then
Uri uri = Uri.fromFile(file);
intent.putExtra(Intent.EXTRA_STREAM , uri);
And send the attachment...

Related

Attach inputstream to email

I have an android apk expansion file and in there are some PDF's.
In the official documentation they access the files inside the .obb via Inputstream. I am able to access the files inside the .obb via the inputstream.
Now I want to attach one of the files to an email with Intent. The E-Mail Intent works perfectly fine with files from the assets, so the problem is attaching the Inputstream.
How can I attach the PDF into the mail directly from the .obb?
Solved it!
You have to convert the Inputstream to a Temorary File, get the Uri of that file and attach it to the email Intent.
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("application/pdf");
try {
ZipResourceFile expansionFile = new ZipResourceFile("Path to .obb file");
InputStream fileStream = expansionFile.getInputStream("Path inside .obb");
String downloadordner = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); //used for temp storage
File tempFile = new File(downloadordner+"/"+"filename.pdf");
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(fileStream, out);
Uri theUri = Uri.fromFile(tempFile);
i.putExtra(Intent.EXTRA_STREAM, theUri);
startActivity(Intent.createChooser(i, "PDF versenden..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(preisliste.this, "Es wurde kein E-Mail Client gefunden.", Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
Log.v("Datei nicht gefunden","Main Expansion");
}

Share screenshot from internal storage android

I want to share the screenshot that gets stored in internal storage but all I'm getting while sharing is a blank screen. I came to know that another app cannot use ones won app private data. This is the code I have used to save the image :
File path = new File(getApplicationContext().getDir("Default", Context.MODE_ENABLE_WRITE_AHEAD_LOGGING),"myapp");
File directory = new File(path.getAbsolutePath());
directory.mkdirs();
String filename = "myapp.png";
File yourFile = new File(directory, filename);
try
{
FileOutputStream out = new FileOutputStream(yourFile, true);
bitmap.compress(Bitmap.CompressFormat.PNG, 90,out);
out.flush();
out.close();
send(yourFile);
}catch (IOException e)
{
e.printStackTrace();
}
And the share intent is:
public void send(File path)
{
Uri uri = Uri.fromFile(path);
Log.d("uri", String.valueOf(path));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My App");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share via"));
}
The path in which the image is getting saved and the value of path is :
/data/user/0/com.sample.myapp/app_Default/myapp/myapp.png
Now how would I make sure that the screenshot is getting accessed and made available for sharing.
You are getting image URI not Real Image path
to get Real path check this
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
just pass this image uri and get full image path
I solved it by exporting the image to external storage and then sharing.
String url = null;
try {
url = MediaStore.Images.Media.insertImage(getContentResolver(), path.getAbsolutePath(), path.getName(), path.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Uri uri = Uri.parse(url);

Share audio file from the res/raw folder thorugh Share Intent in Android

I'm trying to share an audio file from my res/raw folder. What I've done so far is:
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound); //parse path to uri
Intent share = new Intent(Intent.ACTION_SEND); //share intent
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share sound to"));
When I choose to share it on GMail, for example, it says something like "Failed to attach empty file". Looks like I'm not getting the right file path, so I'm basically sharing nothing. What am I doing wrong?
Any help would be much appreciated.
Copy the audio file from the resource to external storage and then share it:
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = getResources().openRawResource(R.raw.sound);
fileOutputStream = new FileOutputStream(
new File(Environment.getExternalStorageDirectory(), "sound.mp3"));
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
inputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/sound.mp3" ));
intent.setType("audio/*");
startActivity(Intent.createChooser(intent, "Share sound"));
Add WRITE_EXTERNAL_STORAGE permission to AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
What am I doing wrong?
Few apps handle android.resource Uri values correctly. Your choices are:
Drop the feature, or
Copy the data from the resource into a file, then use FileProvider, perhaps in conjunction with my LegacyCompatCursorWrapper, or
Use my StreamProvider, which can serve raw resources directly, or
Copy the data from the resource into a file, then use Uri.fromFile(), but this looks like it will stop working with the next version of Android, based on preliminary results from testing with the N Developer Preview
EDIT: It was causing a NullPointException. This is what was I doing:
File dest = Environment.getExternalStorageDirectory();
InputStream in = getResources().openRawResource(R.raw.sound);
try
{
OutputStream out = new FileOutputStream(new File(dest, "sound.mp3"));
byte[] buf = new byte[1024];
int len;
while ( (len = in.read(buf, 0, buf.length)) != -1){
out.write(buf, 0, len);
}
in.close();
out.close();
}catch (Exception e) {}
final Uri uri = FileProvider.getUriForFile(Soundboard.this, "myapp.folagor.miquel.folagor", dest); //NullPointerException right here!!
final Intent intent = ShareCompat.IntentBuilder.from(Soundboard.this)
.setType("audio/*")
.setSubject(getString(R.string.share_subject))
.setStream(uri)
.setChooserTitle(R.string.share_title)
.createChooserIntent()
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
The code was just fine. The only problem was that on the Manifest's permisions, I had "WRITE_EXTERNAL_STORAGE" instead of "android.permissions.WRITE_EXTERNAL_STORAGE". So I was not having permision to write in the external storage, which caused a FileNotFoundException due to the lack of permision. Now it works fine!

Displaying PDF file with Adobe Reader

I created a class openPDF which takes a byte array as input and displays the PDF file with Adobe Reader. Code:
private void openPDF(byte[] PDFByteArray) {
try {
// create temp file that will hold byte array
File tempPDF = File.createTempFile("temp", ".pdf", getCacheDir());
tempPDF.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempPDF);
fos.write(PDFByteArray);
fos.close();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(tempPDF);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} catch (IOException ex) {
String s = ex.toString();
ex.printStackTrace();
}
}
When I pass the intend , the error from adobe reader is "Invalid file path". I read all other posts related to downloading and viewing PDF in android but dint help much. Any suggestions?
I think the issue is that other apps have no access to the files in your app's private data area (like the cache dir).
Candidate solutions:
changing the file's mode to MODE_WORLD_READABLE so that it can be read by other apps
...
String fn = "temp.pdf";
Context c = v.getContext();
FileOutputStream fos = null;
try {
fos = c.openFileOutput(fn, Context.MODE_WORLD_READABLE);
fos.write(PDFByteArray);
} catch (FileNotFoundException e) {
// do something
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fos!=null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
String filename = c.getFilesDir() + File.separator + fn;
File file = new File(filename);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
...
or write the pdf file to the /sdcard partition.
you can use android.os.Environment API to get the path, and remember to add the permission to your app's AndroidManifest.xml file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Regards
Ziteng Chen
I made this code to open an especific .pdf file existing in Dowloads folder with Adobe's application
File folder = new File(Environment.getExternalStorageDirectory(), "Download");
File pdf = new File(folder, "Test.pdf");
Uri uri = Uri.fromFile(pdf);
PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("com.adobe.reader");
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
It works for me. So i guess your problem can be the temprorary file. Try to write the file to sdcard. To do this you will need add android.permission.WRITE_EXTERNAL_STORAGE to your AndroidManifest.xml.

Setting file name for saving .JPG

I am stuck. I am converting a LinearLayout to a Bitmap, saving it, and then E-mailing it. The issue I have is I want to set the file name so it overwrites the previous file name. The main purpose is to email the LinearLayout as an image. From what I read you have to save it to the SD card first. I am fine with that but I only want to have one saved image at all times. I am getting a file name with what seems like a random 13 digit file name like (1329676773253.jpg) Here is the code.
void image() {
llImage.setDrawingCacheEnabled(true);
test2 = Bitmap.createBitmap(llImage.getDrawingCache());
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "001");
values.put(Images.Media.DISPLAY_NAME, "ast.jpg");
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri2 = getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
try {
OutputStream outStream = getContentResolver()
.openOutputStream(uri2);
test2.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
Log.d("done", "done");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
final Intent emailIntent = new Intent(
android.content.Intent.ACTION_SEND);
emailIntent.setType("text/html");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
emailIntent.putExtra(Intent.EXTRA_STREAM, uri2);
emailIntent.setType("image/png");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
Html.fromHtml("" + finalEmail));
startActivity(Intent.createChooser(emailIntent, "Email:"));
}
You could simply write to file with FileOutputStream:
FileOutputStream outStream = new FileOutputStream("filename.jpg");

Categories

Resources