The PDF file is not saved in the Android 11 Download folder - android

Inside my software, a list of user information is generated offline as a PDF file. I tested this operation on Android 7 and 8 and everything was fine. But when I test on Android 11, the file is not generated. I was looking for a solution but I did not really find the complete source and training in this field.
I was able to create a PDF file via Intent, but inside another software, I saw that as soon as I clicked the save button, a folder with the program name was created in the Documents folder and the file was created inside.
This is the code I use to save the PDF file in the Download folder and it works for Android 7 and 8.
public void savePdfFileToStorage(String pdfTitleHeader, String currentTime, PdfDocument pdfDocument, Context context) {
String PdfDir=Environment.getExternalStorageDirectory() + "/Download/Apple";
File dir=new File(PdfDir);
if (!dir.exists())
dir.mkdir();
String fileName = pdfTitleHeader + "_" + todayDate() + "_" + convertToEnglishDigits(currentTime) + ".pdf";
File file = new File(PdfDir,fileName);
if (!file.exists()) {
try {
file.createNewFile();
Log.e(TAG, "savePdfFileToStorage: " + "file created" + file.getName() + "path: " + file.getPath());
} catch (IOException e) {
e.printStackTrace();
}
}
try {
pdfDocument.writeTo(new FileOutputStream(file));
Log.e(TAG, "savePdfFileToStorage: pdf Wrote in file");
Toast.makeText(context, "فایل PDF در پوشه Download/Apple حافظه داخلی ذخیره شد.", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "فایل PDF ساخته نشد.", Toast.LENGTH_LONG).show();
}
pdfDocument.close();
}
And I wrote these codes in the Manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application>
...
android:requestLegacyExternalStorage="true"
...
</application>
Please advise where I should add the code to solve the storage problem in Android 11.

This code generates a similar name: allTransaction 20220202 10:15:23 .pdf
The : is a forbidden character in file names and paths.

I used the following code and was finally able to save the file in the Documents folder.
public void savePdfFileToStorage(String pdfTitleHeader, String currentTime, PdfDocument pdfDocument, Context context) {
File dir;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/Apple");
else dir = new File(Environment.getExternalStorageDirectory() + "/Apple");
if (!dir.exists())
if(!dir.mkdir())
return;
String fileName = pdfTitleHeader + "_" + todayDate() + "_" + convertToEnglishDigits(currentTime) + ".pdf";
File file = new File(dir, fileName);
if (!file.exists()) {
try {
file.createNewFile();
Log.e(TAG, "savePdfFileToStorage: " + "file created" + file.getName() + "path: " + file.getPath());
} catch (IOException e) {
e.printStackTrace();
}
}
try {
pdfDocument.writeTo(new FileOutputStream(file));
Log.e(TAG, "savePdfFileToStorage: pdf Wrote in file");
Toast.makeText(context, "فایل PDF در پوشه Download/Appleحافظه داخلی ذخیره شد.", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "فایل PDF ساخته نشد.", Toast.LENGTH_LONG).show();
}
pdfDocument.close();
}

Related

Cannot save string to file on android

I am trying to create txt file and write to it on sdcard in android. I am getting "Directory not created" error. path.mkdirs() should create needed directories, shouldn't it ? I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in AndroidManifest.xml and I have turned on storage permission for app.
Android version: 7.0
public void addData(View v) {
wordList.add(inAddWord.getText().toString());
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File file = new File(path, "wordDatabase.txt");
try {
if(!(path.exists() && path.isDirectory())) {
while (!path.mkdir()) {
Log.e("Path", "Directory not created");
}
}
OutputStream os = new FileOutputStream(file);
os.write((inAddWord.getText().toString() + "\n").getBytes());
os.close();
} catch (IOException e) {
e.printStackTrace();
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
On Android 6+ you should add code to ask the user to confirm the permissions you request in manifest.
Google for runtime pemissions.

Android create a text file on internal storage, email it, then delete the file

I want to be able to create a text file with data inside of it, email that file, and then get rid of it on my Android device.
Below is what I have so far but it is giving me the error:
java.io.FileNotFoundException: /20150719_130219: open failed: EROFS (Read-only file system)
Code:
BufferedWriter writer = null;
try {
//create a temporary file
String report = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
File logFile = new File(report);
writer = new BufferedWriter(new FileWriter(logFile));
for (Map.Entry entry : cbh.data.entrySet()) {
reportText.append(entry.getKey() + ", " + entry.getValue() + "\n");
writer.write(entry.getKey() + ", " + entry.getValue() + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception e) {
}
}
First you need to provide permissions in your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Second in your code you are just generating the name of the file but its complete path is not defined where it will be saved.
Environment.getExternalStorageDirectory()
will return the path of sdcard
You can write this
String report = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
String fileName = Environment.getExternalStorageDirectory()+ report+".txt";
File file = new File(fileName);

unable to save the file in the external directory in android.

In android, how to write the file in the external directory in the desired folder.
i have use the following coding, but it doesn't seems to work.
File r = Environment.getExternalStorageDirectory();
File oD = new File(root.getAbsolutePath() + File.separator + "web_dir");
if (!outDir.isDirectory()) {
outDir.mkdir();
}
try {
if (!outDir.isDirectory()) {
throw new IOException(
"Unable to create directory");
}
File outputFile = new File(outDir, "web_file");
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
writer.write(new String("hello"));
Toast.makeText(context.getApplicationContext(),
"Successfully saved to: " + outputFile.getAbsolutePath(),
Toast.LENGTH_LONG).show();
writer.close();
} catch (IOException e) {
Log.w("et", e.getMessage(), e);
Toast.makeText(context, e.getMessage() + " Unable to write to external"
+"storage.", Toast.LENGTH_LONG).show();
}
First make sure you have permission in your manifest file to write external storage.
<!-- Depends on your requirements -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ref: Saving Files - Android Developer Doc
below is the sample code to write file to external storage.
private void writeToSDFile(){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: "+root);
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to "+file);
}
Hope it will help you..
What's the error message? As Mike said, your are probably missing the correct permission. Add the following to your manifest, as a child of the <manifest> tag:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Writing a zip to internal storage -- file doesn't exist after download completion

I used a tutorial to download a zip into a subdirectory of my application's internal storage. I wrote the zip to /data/data/my.package.name/files/mySubDirectory/the.zip.
But, when I check to see whether the zip exists, it doesn't:
String fileDirectory = this.getFilesDir().getAbsolutePath() + "/mySubDirectory/the.zip";
File file = new File(fileDirectory);
if(file.exists()) {
Log.e(this.class.getName(), "file exists");
} else {
Log.e(this.class.getName(), "file doesn't exist");
}
I verified that fileDirectory is the same path as the File outFile for the FileOutputStream.
What could be the problem?
Try getting your file path as below :
String fileDirectory=Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "data" + File.separator + "data" + File.separator+ getActivity().getPackageName()+ File.separator +"mySubDirectory"+File.separator+"the.zip";
Using this SO question, I created a subdirectory using this example:
File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myfile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file
The problem is that I didn't expect the subdirectory to be prepended with "app_", so I was looking for the zip in the wrong place.
Try using getFilesDir() + "/" subdirectory + "/" "the.zip"
Without the getabsolutepath().
That is what I used could be the issue.
OK maybe you problem is with permissions do you see the file in the DDMS under data/data/package/files ? Check the permissions for the files
Here is my code
String path = getFilesDir() + "/"
+ subDirName + "/";
File file = new File(path);
file.mkdirs();
setReadable(file);
I use the following to make the file readable
#TargetApi(9)
private void setReadable(File file) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
try {
Runtime.getRuntime().exec(
"chmod 777 " + file.getCanonicalPath());
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
file.setReadable(true, false);
}
}
}

Android Local KML File & Google Maps

I am trying to write and then load a KML file using Google Maps via an Intent. I have tried both internal and external storage for the KML file - it seems to be writing correctly, but I keep getting the following error Toast in Google Maps:
No results found for:file:///data/data/[my app package path]/kml_to_view.kml
Writing To File
File dir = context.getFilesDir();
//File dir = Environment.getExternalStorageDirectory();
Log.d(TAG, "Writing to dir: " + dir);
File kmlFile = new File(dir, KML_FILE_NAME);
FileOutputStream fos;
try
{
kmlFile.createNewFile();
fos = context.openFileOutput(KML_FILE_NAME, Context.MODE_WORLD_READABLE);
//fos = new FileOutputStream(kmlFile);
fos.write(kmlData.getBytes());
fos.close();
isKMLPrepared = true;
Toast.makeText(context, "file write successful", Toast.LENGTH_LONG);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG);
e.printStackTrace();
}
As you can see I have the pieces necessary to write either to internal storage or external and I have tried both.
Sending KML To Maps
File dir = context.getFilesDir();
Log.d(TAG, "Local file path: " + dir);
readInternalStoragePrivate(KML_FILE_NAME);
mapsIntent = new Intent(Intent.ACTION_VIEW);//Uri.parse("http://maps.google.com/maps"));
//String uri = "geo:0,0?q=file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + KML_FILE_NAME;
String uri = "geo:0,0?q=file://" + context.getFilesDir().getAbsolutePath() + "/" + KML_FILE_NAME;
Log.d(TAG, "URI: " + uri);
mapsIntent.setData(Uri.parse(uri));
Again I have tried reading both internal and external locations when sending a path to the Maps app.
Any idea what I need to do to get the Maps app to read and process a locally stored KML file? I have read a number of other posts, but I have yet to find a solution to my problem.

Categories

Resources