Android Local KML File & Google Maps - android

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.

Related

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

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();
}

I am unable to create a folder in external sd card in android

I have tried this code but it always creates a folder in the phone's internal memory.
String externalDataPath = Environment.getExternalStorageDirectory() + "/yourFolder";
File f = new File(externalDataPath);
try {
if (!f.exists()) {
f.mkdir();
}
externalDataPath = externalDataPath + "/" + filename;
f = new File(externalDataPath);
if (!f.exists())
f.createNewFile();
externalDataPath = Environment.getExternalStorageDirectory().toString();
} catch (IOException e) {
e.printStackTrace();
}
Also, I have added EXTERNAL_WRITE PERMISSION in Manifest file..
Any help would be highly appreciated.
A path to your app specific folder on a removable micro sd card can be obtained by using the second item returned by
getExternalFilesDirs()

Android, how to prevent internal storage files to be deleted when the app is uninstalled

I'm developing an app which stores few setting in two .xml files, saved on internal storage. I need to save them in there, so please don't answer me "Save them on SD-cards".
I try to uninstall an then re-install (from Android Studio) my app to see if the android:allowBackup="true" works also for internal stored file but the answer was no.
Is this because I done the re-install from the IDE or I need to add some code somewhere?
Thanks for help.
Starting API level 29 there is the "hasFragileUserData" manifest flag
The documentation states that
If true the user is prompted to keep the app's data on uninstall.
May be a boolean value, such as "true" or "false".
Sample code:
<application
....
android:hasFragileUserData="true">
You can save those file using Environment.getExternalStorageDirectory() This stores on the external storage device. Dont get confused with the term external storage as the SD card. SD card is the secondary external storage. But Environment.getExternalStorageDirectory() returns top-level directory of the primary external storage of your device which is basically a non removable storage.
So the file path can be /storage/emulated/0/YOURFOLDER/my.xml
So even if you uninstall the app, these files will not get deleted.
You can use this snippet to create a file in your primary external storage:
private final String fileName = "note.txt";
private void writeFile() {
File extStore = Environment.getExternalStorageDirectory();
// ==> /storage/emulated/0/note.txt
String path = extStore.getAbsolutePath() + "/" + fileName;
Log.i("ExternalStorageDemo", "Save to: " + path);
String data = editText.getText().toString();
try {
File myFile = new File(path);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Toast.makeText(getApplicationContext(), fileName + " saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Don't forget to add below permission in Android Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
You can then read that file as below:
private void readFile() {
File extStore = Environment.getExternalStorageDirectory();
// ==> /storage/emulated/0/note.txt
String path = extStore.getAbsolutePath() + "/" + fileName;
Log.i("ExternalStorageDemo", "Read file: " + path);
String s = "";
String fileContent = "";
try {
File myFile = new File(path);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((s = myReader.readLine()) != null) {
fileContent += s + "\n";
}
myReader.close();
this.textView.setText(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), fileContent, Toast.LENGTH_LONG).show();
}

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);

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);
}
}
}

Categories

Resources