Android: Create and Download PDF files to Downloads directory - android

In my Android App, in one of the activity, there is a "PDF Download" button. When this button is clicked, I create a PDF and then download it to the "Downloads" directory. Following is my code which runs on the click event of the button:
public void createAndDownloadPDF()
{
try
{
PdfDocument document = new PdfDocument();
View content = this.findViewById(android.R.id.content);
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(content.getWidth(),
content.getHeight() - 20, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
content.draw(page.getCanvas());
document.finishPage(page);
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyhhmmss");
String pdfName = "pdfdemo"
+ sdf.format(Calendar.getInstance().getTime()) + ".pdf";
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), pdfName);
try
{
outputFile.createNewFile();
OutputStream out = new FileOutputStream(outputFile);
document.writeTo(out);
document.close();
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
Please note that I added the required WRITE permission to the MANIFEST file and also asking for the permission at runtime. So, there is no issue of permissions.
When I debug the code, I notice that "outputFile" variable holds this path:
/storage/emulated/o/Download/pdfdemo07052017121233.pdf
My users will never find above path in their mobile. So, they will have no clue where their PDF got saved. I want that when users click on "Downloads" icon on their mobile, they should see the PDF file they downloaded from the app.
So, I think if I can sort out the following line:
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), pdfName);
my work will be done. What should be the path I use so that my PDF files get saved / downloaded in the "Downloads" directory? I researched over the internet, but did not find any concrete solution.

Try this:
File outDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
If this doesn't work, evaluate the chance of having your PDF file previously generated and saved into a folder inside your Assets folder. If this can be the case, after the above line you insert this:
copyAssets("XXX",outDir.toString());
Where "XXX" is the name of the folder inside your Assets folder which will contain the PDF file. This will copy the contents of XXX to DOWNLOADS/XXX on your device.

Related

Create a folder if it doesn't exist, then create a file and share it

I have an issue with my sharing option.
The option was perfectly well working (and I have saved it before trying some modifications) but I have tried to modify something and I cannot reach my goal).
The purpose is : click on the option in a menu, click on share, if the folder "test folder" doesn't exists in the "MUSIC" folder, create it, if it already exists, copie the sound, put it in the folder previously created and then use it as an extra in a SEND intent.
case R.id.share:
if (isStoragePermissionGranted()) {
File outputFile = new File("");
InputStream is = getResources().openRawResource(((Sound) adapter.getItem(index)).getMpsound());
try {
File outputDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC), "Test folder");
outputFile = new File(outputDir, getResources().getResourceEntryName(((Sound) adapter.getItem(index)).getMpsound()) + ".mp3");
if (outputDir.exists()) {
byte[] buffer = new byte[is.available()];
is.read(buffer);
OutputStream os = new FileOutputStream(outputFile);
os.write(buffer);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", outputFile));
share.putExtra(Intent.EXTRA_TEXT, "\"" + ((Sound) adapter.getItem(index)).getTitle_show() + "\" shared by my app");
startActivity(Intent.createChooser(share, "Share Sound File"));
} else {
outputDir.createNewFile(); //plus add code as below to share the sound after creating the folder
}
} catch (IOException e) {
e.printStackTrace();
}
}
I'm not able to create the folder and if I create it manually, the code is working well because the mp3 appears in the folder, and right after I have an error that says :
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Music/my app/sound_test.mp3
So... the app is able to access the folder to create the sound but for an unknown reason, I have this issue.
What did I do wrong ?
So, for the ones who are coming in few days, months, years with the same problem :
As CommonsWare said it, the issue in accessing the folder was from the FileProvider. After configure it properly with the good path, I had no more issue.
For the part concerning the creation of a new folder, .createNewFile() doesn't seems to be the right way. It's necessarry to use .mkdir()
And to end it, the part concerning the delete of the files in the folder, you will have your answer there :
File dir = new File(Environment.getExternalStorageDirectory()+"Dir_name_here");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
Source : How to delete all files in a directory java android app? Current code is deleting the that folder

Storage in android studio

I am trying to pull multiple images from gallery and place in grid view , Unfortunately I am not able to do so, Can you help me with that. And also I made a folder in sd card and I m trying to store audio as well as photographs in the same folder. Can you help me with that as well?
I am using android 2.3.
So I have included this code inside the button click but on click of button it has created the folder but its not storing the file inside the folder. On click of the button every other thing is working, its opening the gallery and its calculating numpic. I am not sure why its not storing the file in CN Video folder.
public void onClick(View v) {
Intent pass_data = new Intent(MainRecord.this, OpenGallery.class);
pass_data.putExtra("numpic",numpic);
startActivity(pass_data);
// Saving Audio recorded file to directory
File f = new File(Environment.getExternalStorageDirectory() + "/CNvideo");
if(f.isDirectory()) {
//Write code for the folder exist condition
}else {
// create a File object for the parent directory
File CNvideoDirectory = new File("/sdcard/CNVideo/");
// have the object build the directory structure, if needed.
CNvideoDirectory.mkdirs();
// create a File object for the output file
String filename = getfilename();
File outputFile = new File(CNvideoDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
try {
FileOutputStream fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}};

Creating a file unsing openFileOutput() which is visible to other applications

I'm using the openFileOutput() to create a new txt file. I need the file to be visible from other applications (as well as from a PC when the Android device is connected via USB. Ive tried using .setReadable(true); but this does not seem valid. Please advise how I should declare the file is visible / public.
try {
textIncoming.append("saving");
final String STORETEXT = "test.txt";
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(STORETEXT, 0));
out.setReadable(true);
out.write("testing");
out.close();
}
catch (Throwable t) {
textIncoming.append("not saving");
}
Ive changed my program to use getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), but for some reason it returns a path /storage/emulated/0/Documents, and I cant even find this folder on the device. Ive looked at the files on the android device using ES file explorer but cant find the folder or file I'm trying to create (Plus I want these in an documents folder on the SD card, so it seems that its not giving me a pointer to the SD card at all, and not creating the folder, and not creating the file. Following is my updated code, please advise
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
File myDir = new File(root + "/Saved_Receipts");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "DRcpt-" + n + ".xml";
textIncoming.append(root);
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
Save it to sdcard if you want anyone to be able to read it.
This android documentation should tell you what you need to do.
https://developer.android.com/guide/topics/data/data-storage.html#filesExternal
openFileOutput() documentation says:
Open a private file
So the file that it creates won't be visible to other apps, unless you copy it to another directory that is visible. In that case, you have to save your data in what's called "external storage" which is shared with other apps. Use the code at this link.

unable to open a word file using android app

I have saved a file with .docx extension in my app.the file is saved in the sdcard. The file appears as a word file in my sdcard but I am unable to open it (using polaris or any other default software) and message"unsupported file" appears.
When I save the file with .txt extension, I can open it.
public void Savedoc(View v)
{
String filename = "file" + sn + ".docx";
String filepath = "MyFileStorage";
myExternalFile = new File(getExternalFilesDir(filepath), filename);
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(ly.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
thank you alexandru ...but now i get an error message on running the app stating "The Javadoc for this element could neither be found in the attached source nor the attached Javadoc".pls help...
You'll need to use Apache POI in order to correctly create a .docx file.
I've found this answer with a code snippet:
XWPFDocument document = new XWPFDocument();
XWPFParagraph tmpParagraph = document.createParagraph();
XWPFRun tmpRun = tmpParagraph.createRun();
tmpRun.setText("LALALALAALALAAAA");
tmpRun.setFontSize(18);
document.write(new FileOutputStream(new File("yourpathhere")));
You may find more information about how to use XWPF here.

where to write a text file and how to set it up for an sd card

I know this is a popular question but I have looked at all of the other responses and none of them seem to work. What I want to do is write some code to a text file. My first question: is there a way to view that text file without writing code to the console? Second, I dont know where in my phone it goes and I want to see it to help trouble shoot, so if you know how to do that too, it would be great. So now I will give you an overview of what is happening. When I start my program it checks to see if the file exists, if it doesn't it reads a file out of my assets folder and copies that info and sends it to a file into the sd card. If it exits it reads the info from the sd card. Next if I press a button and change numbers and print it to my sd card again then I close it using task managers then when I come back the original information is here. I don't feel like it is being able to find my sd card location. So far I have used.
File outfilepath = Environment.getExternalStorageDirectory();
String FileName = "ExSettings.txt" ;
File outfile = new File(outfilepath.getAbsolutePath()+"/TimeLeft/"+FileName);
File outfilepath = Environment.getExternalStorageDirectory();
String FileName = "ExSettings.txt" ;
File outfile = new File(outfilepath, FileName);
Any Ideas?
This is a function that I wrote which will take in a list array and write to a file line by line.
It will use the path in fileName to make a new folder called myfolder in the root of the SDCard, an inside will be your file of newtextfile.txt.
List<String> File_Contents = new ArrayList<String>();
File_Contents.add("This is line one");
File_Contents.add("This is line two");
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/myfolder/newtextfile.txt");
f.mkDirs();
try {
BufferedWriter out = new BufferedWriter(new FileWriter(f));
for (int x = 0; x < File_Contents.size(); x++) {
out.write(File_Contents.get(x));
out.write(System.getProperty("line.separator"));
}
out.close();
return true;
} catch (Exception e) {
return false;
}

Categories

Resources