//Save PDF file
//Create time stamp
Date date = new Date() ;
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("_yyyy_MM_dd_HH_mm_ss").format(date);
String filePath = Environment.getExternalStorageDirectory() +"/"+ "Allotment" +timeStamp+ ".pdf";
File myFile = new File(filePath);
try {
OutputStream output = new FileOutputStream(myFile);
pdfDocument.writeTo(output);
output.flush();
output.close();
Toast.makeText(AllotmentDoc.this, "PDF Created Succesfully", Toast.LENGTH_LONG).show();
Toast.makeText(AllotmentDoc.this, "PDF Saved On Memory", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
I want to save my pdf file that's why I wrote some line of code. But it works on some device and doesnt work on some other device. What is the problem. how can i solve it.
I think you are facing this problem in some deviece because of
Environment.getExternalStorageDirectory()
You can use
Environment.getExternalStorageDirectory().getAbsolutePath();
Have in mind though, that getExternalStorageDirectory() is not going to work properly on some phones e.g. Galaxy Tab 2, Motorola razr maxx, as it has 2 cards /mnt/sdcard and /mnt/sdcard-ext - for internal and external SD cards respectfully. You will be getting the /mnt/sdcard only reply every time.
Related
I have tried about 10 answers to a similar question, but none of them were successful. Something might be out of date. Please give an answer for today.
Simple task:
I want my app to be able to send a file with an image to e-mail or whatsapp.
I put the file with the image in the application resources in the folder Drawable.
Its size is 5 MB.
How to do this in Java?
I'm asking for code, not links to similar answers. I've tried most of them already.
Some decisions came to null.bin.
Some don't send anything at all and throw an error.
Perhaps I am not specifying any permissions.
Something else is possible.
I'm new.
I would like an answer with comments (what I am writing and why)
// step 1. I put the picture in the folder Drawable
// clicking on the button sends the picture through the messenger to other users
public void onClick_sendMyImage(View v) {
// Step 2.Convert PICTURE to Bitmap
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
saveImage(bitmap); // 3. save the PICTURE in the internal folder
send(); // 4.sending PICTURE (function code below)
}
// step 3. Saving the image in the internal folder:
private static void saveImage(Bitmap finalBitmap){
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
//Log.i("Directory", "==" + myDir);
myDir.mkdirs();
String fname = "image_test" + ".jpg";
File file = new File(myDir, fname);
if(file.exists()) file.delete();
try{
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Step 4. Sending the saved PICTURE
public void send(){
try{
File myFile = new File("/storage/emulated/0/saved_images/image_test.jpg");
// for something I create this type (so it is said in one of the answers)
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(type);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(myFile));
Intent intent1 = Intent.createChooser(intent, "what do you want to send ?");
startActivity(intent1);
}catch (Exception e){
Toast.makeText(this, "repeat sending", Toast.LENGTH_SHORT).show();
}
}
Sending an image from an app turned out to be not a good idea.
The image cannot be edited if necessary.
Over time, you may want to add more images, etc..
I did it differently, and it turned out better:
I put the image on GoogleDisk.(now I can change it at any time without having
to ask users to reinstall the application every time the picture changes).
I placed a link to the picture in the FireBase Database. (I also placed a banner with a picture here.).
I connected the application to the Firebase Database.
In the activity I made a RecyclingView, where I get a banner(s) and a link(s) to the original image(s). The user can download this link or send it through whatsapp anywhere and download the original picture in good quality (A1, 2.5Mb).
thanks, guys..
I thank the guys for the tips, especially mr.Blackapps. In this case, you really can't do without a FileProvider.
I'm a beginner working on an Android app that uses the gcacace SignaturePad library to capture the signature of my user. My goal is to take the signature, compress it down into a JPEG, and then write that information to a file on the users phone so the picture can be accessed later.
I am currently getting no errors or crashes when I run the code, yet no directory or file is being created when I test the app out on my device(Google Pixel 2). Can anyone give me a hand figuring out where the problem is? I've thrown my head against a wall this entire morning and still don't know.
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("images", Context.MODE_PRIVATE);
if (!directory.exists()) {
directory.mkdirs();
}
File myPath = new File(directory, "1.jpg");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(myPath);
} catch (Exception e) {
e.printStackTrace();
}
signaturePad.getSignatureBitmap().compress(Bitmap.CompressFormat.JPEG, 90, fOut);
Bitmap signature = signaturePad.getSignatureBitmap();
int bytes = signature.getByteCount();
try {
fOut.write(bytes);
fOut.flush();
fOut.close();
} catch (IOException ex) {
ex.printStackTrace();
}
Toast.makeText(activity_signature_pad.this, "Signature Saved", Toast.LENGTH_SHORT).show();
The code in your question writes to what the Android SDK refers to internal storage. That is private to your app; ordinary users do not have access to it (including you, except when using developer tools).
You appear to want to write to external storage. For that, use:
File directory = new File(getExternalFilesDir(null), "images")
I am writing a camera application for the android platform. I am using the CameraKitView Library for producing my camera view. Everything else including accessing the camera is working as expected except for actually capturing and saving the image. minimum sdk is 15 and target sdk and compile sdk is 28. The code for saving the image is as shown below
cameraKitView.captureImage(new CameraKitView.ImageCallback() {
#Override
public void onImage(CameraKitView cameraKitView, byte[] photo) {
File savedPhoto = new File(Environment.getExternalStorageDirectory(), "pchk.jpg");
try{
FileOutputStream outputStream = new FileOutputStream(savedPhoto.getPath());
outputStream.write(photo);
outputStream.close();
}catch (java.io.IOException e){
e.printStackTrace();
}
}
});
Thank you in advance for your assistance
First of all verify that your file or folder where you want to save a file is exists or not, if not create them
capturedFolderPath is a path of the folder where you want to create the file
File folderFile = new File(capturedFolderPath)
if (!folderFile.exists()) {
folderFile.mkdirs();
}
String imageNameToSave = "xyz.jpg";
String imagePath = capturedFolderPath
+ File.separator + imageNameToSave + ".jpg";
File photoFile = new File(imagePath);
if (!photoFile.exists()) {
photoFile.createNewFile();
}
after creating write the bytes on the file like this
FileOutputStream outputStream = new FileOutputStream(photoFile);
outputStream.write(bytes);
outputStream.close();
I have a function that I want to automatically take a screenshot and then upload it to the users preferred email app.
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".png";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.PNG, quality, outputStream);
outputStream.flush();
outputStream.close();
File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + now + mPath);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// set the type to 'email'
emailIntent .setType("vnd.android.cursor.dir/email");
String to[] = {"Enter your email address"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Journey : ");
startActivity(Intent.createChooser(emailIntent , "Select your preferred email app.."));
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
This is my function. It is taking the screen shot automatically and its store it on my local device. It is also prompting the user to select their email app. Then I select an app it says "unable to attach file" . I have read and write permissions in my manifest.
The other app may not have access to external storage. Plus, your code will crash on Android 7.0+, once you raise your targetSdkVersion to 24 or higher.
Switch to using FileProvider and its getUriForFile() method, instead of using Uri.fromFile().
And, eventually, move that disk I/O to a background thread.
check this link -
https://www.javacodegeeks.com/2013/10/send-email-with-attachment-in-android.html
and How to send an email with a file attachment in Android
Hope this help.
The problem was :
Uri path = Uri.fromFile(filelocation);
Instead I used :
File filelocation = new File(MediaStore.Images.Media.DATA + mPath);
Uri myUri = Uri.parse("file://" + filelocation);
Hopefully this helps anyone facing the same problem.
I wrote a small app, which creats a XML file on my Android device. No I try to copy it from my phone to my Windows PC. In Windows Explorer I can't see this file specific file, on my phone I can see this file with various file explorers. When I reboot my phone, the file appears in Windows Explorer, but I can't copy it to my desktop.
Here is my code which creates my file:
String filename = "myfile.xml";
String dir = Environment.getExternalStorageDirectory().getPath()+"/"+c.getResources().getString(R.string.app_name);
createDir(dir);
File file = new File(dir,filename);
FileWriter out=null;
try {
String xml = createXml();
try {
out = new FileWriter(file);
out.write(xml);
out.close();
} catch (Exception e) {
out.close();
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
My guess is, this code doesn't free the file handle so Androids MTP cannot access this file. This would also explain, why the file is shown and could be deleted (but not able to be transfered to my PC) after rebooting my phone.
Any suggestions what goes wrong?
I think you should refresh the media scanner for that file
sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageAdded))
);