Not able to write file on android - java

I have been trying to write PDF files on android ,when i am using internal storage it shows no error but i am unable to see the file created and if i change path to external storage i get permission denied even though i have given permission in my manifest file.
I have creating a class which i am calling from activity to write files it fetches data from database.
Here is the code.
public boolean createPdfFile(String path, Employee employee,String month,Context context){
boolean status=false;
if(path!=null && employee!=null){
Document document=new Document();
try{
if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Toast.makeText(this, "External SD card not mounted", Toast.LENGTH_LONG).show();
}
File sdCard=Environment.getExternalStorageDirectory();
File file=new File(sdCard,month+"_"+employee.getEmployeeName()+".pdf");
PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream(file));
writer.setEncryption(employee.getDateOfBirth().getBytes(),employee.getEmployeeName().getBytes(), PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
document.open();
Paragraph p=new Paragraph();
p.add("Payslip for the month of January");
p.setFont(new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(1, 1, 1)));
p.setAlignment(Element.ALIGN_CENTER);
document.add(p);
PdfPTable table=new PdfPTable(2);
table.setWidthPercentage(100); //Width 100%
table.setSpacingBefore(10f); //Space before table
table.setSpacingAfter(10f); //Space after table
float[] columnWidths = {1.5f, 1.5f};
table.setWidths(columnWidths);
table.addCell("Employee Code");
table.addCell(employee.getEmployeeID());
table.addCell("Department");
table.addCell(employee.getDepartment().getDepartmentName());
table.addCell("Date of Birth");
table.addCell(employee.getDateOfBirth());
table.addCell("Date of Joining");
table.addCell(employee.getDateOfJoining());
table.addCell("Employee Name");
table.addCell(employee.getEmployeeName());
document.add(table);
document.close();
writer.close();
status=true;
}catch (FileNotFoundException e) {
status=false;
Log.e("PDF exception aaa",e.getMessage());
}catch (DocumentException e) {
status=false;
Log.e("PDF exception abc",e.getMessage());
} catch (IOException e) {
status=false;
Log.e("PDF exception",e.getMessage());
}
}
return status;
}

If you are developing for API level 23 or newer you need to explicitly ask the user for permission.
See: https://developer.android.com/training/permissions/requesting.html#perm-check

Related

How to update the existing sticker pack of Whatsapp

I have written codes for adding sticker pack dynamically. But I want to know how to update the sticker pack after adding to whatsapp?
I can add sticker file to the pack which is listed on my app only but it is not reflecting in whatsapp. I tried adding files to the same location (file:///...) from where the pack was sent to whatsapp.
I want to try updating content provider. But how to do that? Can I add files to whatsapp's 'content://...' uri or should I update my app's content provider or anything else?
I am using react-native-whatsapp-stickers module for react-native.
react-native code
invoking after adding single sticker from UI
const addOne = (path, packName) =>{
// log('path ',path[0])
// log('packName ',packName)
RNWhatsAppStickers.addSticker(path[0],packName)
.then(res=>RNWhatsAppStickers.send(packName,packName))
.then(res=>console.log('response ',res))
}
Java code of module RNWhatsAppStickers
#ReactMethod
public void send(String identifier, String stickerPackName, Promise promise) {
Intent intent = new Intent();
intent.setAction("com.whatsapp.intent.action.ENABLE_STICKER_PACK");
intent.putExtra(EXTRA_STICKER_PACK_ID, identifier);
intent.putExtra(EXTRA_STICKER_PACK_AUTHORITY, getContentProviderAuthority(reactContext));
intent.putExtra(EXTRA_STICKER_PACK_NAME, stickerPackName);
try {
Activity activity = getCurrentActivity();
ResolveInfo should = activity.getPackageManager().resolveActivity(intent, 0);
if (should != null) {
activity.startActivityForResult(intent, ADD_PACK);
promise.resolve("OK");
} else {
promise.resolve("OK, but not opened");
}
} catch (ActivityNotFoundException e) {
promise.reject(ERROR_ADDING_STICKER_PACK, e);
} catch (Exception e) {
promise.reject(ERROR_ADDING_STICKER_PACK, e);
}
}
// saving image to same pack
public static void SaveImage(Bitmap finalBitmap, String name, String identifier) {
String root = path + "/" + identifier;
File myDir = new File(root);
myDir.mkdirs();
String fname = name;
File file = new File(myDir, fname);
if (file.exists()){
// Log.d("ReactNative","root "+root);
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.WEBP, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Please give any idea what to do? Thanks
I found the solution on official doc. You have to increase the image_data_Version for that pack after adding new images.
To track the image_data_Version you can query the ContentProvider of your app or Store the image_data_Version somewhere and make changes accordingly .

Trying to send data to text file

Hi there I made a program that consist of jtextfield and couple jbuttons. I want to press a jbutton so that the jtextfields will be save to the computer. Any help will be useful.
I think this will help you..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jTxt_text.getText().isEmpty()) {
JOptionPane.showMessageDialog(rootPane, "Field is empty. Fill the filed and try again.");
} else {
//get the text from the jTextField and save it into a varibale.
String inputText = jTxt_text.getText();
//Where to save the file.
String savePath = "C:/test/sample.txt";
//Creating a file object, file is an abstract representation of file and directory pathnames.
File tempFile = new File(savePath);
//Check wther the file is available or not.
if (!tempFile.exists()) {
try {
//Creates the file if it's not exsising.
tempFile.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
try {
//writing process..
FileWriter tempWriter = new FileWriter(tempFile.getAbsoluteFile());
BufferedWriter tempBufferWriter = new BufferedWriter(tempWriter);
tempBufferWriter.write(inputText);
tempBufferWriter.close();
JOptionPane.showMessageDialog(rootPane, "Text file with the written text is successfully saved.");
jTxt_text.setText(null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Still there's a small problem with this code tempBufferWriter.write(inputText) returns void so.. i don't know how to check wther the process completed successfully from the code itself..

File not found exception when writing away file in java (android)

I have a problem saving a file in android, the FileOutputStream keeps falling back to a FileNotFoundException and thus won't write the file to the external storage.
Yes I do have permission set in the manifest:
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
I've added the code below of the function, can someone explain to me what is going wrong, if it is that it is trying to overwrite an existing file, is there a way to replace that file (the name needs to be static)?
(tips on making the code look nicer are welcome as well)
Bitmap savebitmap = Bitmap.createBitmap(drawView.getDrawingCache());
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files");
if (!mediaStorageDir.exists()){
mediaStorageDir.mkdir();
}
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+File.separator+"Tempsave.png");
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
savebitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Kudos to Guillaume and theV0ID for leading me to the most efficient correct answer.
Below is the example code editted to the working version.
Bitmap savebitmap = Bitmap.createBitmap(drawView.getDrawingCache());
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+File.separator+"Tempsave.png");
pictureFile.getParentFile().mkdirs();
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
savebitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Try this :
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+ File.separator + "Tempsave.png");
pictureFile.getParentFile().mkdirs();
You need to create the file directories if they don't exist. If not the FileOutputStream will throw a FileNotFoundException

Inserting image loses PDF content

I'm trying to insert an image in an existing PDF file but iText puts it on the first page and I'm losing the rest of the page content. How can I insert it without losing existing content?
I used this code:
public static void main(String[] args) {
Document document = new Document(PageSize.A4);
try {
PdfWriter.getInstance(document, new FileOutputStream(
"/home/amira/work/APPS-579/word/generatedMergedDocs/FinalTest/1.pdf"));
document.open();
Image image = Image.getInstance(
"/home/amira/work/APPS-579/word/generatedMergedDocs/FinalTest/a.jpg");
document.add(image);
} catch (DocumentException de) {
de.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
document.close();
}
You're adding the image to an empty document, because you're not reading the original document, just overwriting it.
To modify an existing document with itext with an image, please see the following tutorial which explains it perfectly.

create and save pdf document into external storage in android

I am trying to create a pdf file and save it to sd card. I searched for solutions to my problem but what i found in the net was about creating and saving a file or image. But neither solves my problem. Here's my sample code:
public void createPdf(){
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStoragePublicDirectory("DIRECTORY_PDF") + java.io.File.separator + "droidtext" + java.io.File.separator + "HelloWorld"));
document.open();
document.add(new Paragraph("Hello World"));
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
document.close();
and here's what the logcat says:
02-21 06:28:08.001: W/System.err(859): /mnt/sdcard/DIRECTORY_PDF/droidtext/HelloWorld: open failed: ENOENT (No such file or directory)

Categories