Writing data to a public text file in Android - android

I need to write some data into a text file to be read from standard text editor applications. In my app (running on Android 7.0) compiled with targetSdkVersion 27 I'm doing this trough this method, that works (or at least it seems to work since I got no exeptions):
private void storeLocation(Location location) {
try {
FileOutputStream outputStreamWriter;
outputStreamWriter = this.openFileOutput(logPath.getPath(), Context.MODE_APPEND);
outputStreamWriter.write(("LAT: " + location.getLatitude() + "\n").getBytes());
outputStreamWriter.write(("LON: " + location.getLongitude() + "\n").getBytes());
outputStreamWriter.close();
}
catch (Throwable e) {
Log.e("Exception", "File write failed: " + e.getMessage());
}
}
Variable logPath is defined in this way in application onCreate() event handler:
File logPath = new File("VIPER_" + getCurrentDateTime() + "_" + UUID.randomUUID().toString() + ".log");
I tought to find this file inside application private data folder but it's not here (maybe it's deleted after application closing?).
If I try to specify a different folder (like public downloads folder etc.) I got all sort of exceptions like file not found, read only filesystem, presence of / character in path etc.
There's a (simple) way to allow an application without having to deal with a FileProvider implementation?

The solution I found and that's working for some reason is the following:
logPath = new File( this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "VIPER_" + getCurrentDateTime() + "_" + UUID.randomUUID().toString() + ".txt");
private void storeLocation(Location location) {
try {
final FileOutputStream outputStreamWriter = new FileOutputStream( logPath, true);
final SimpleDateFormat time_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
final String line = time_format.format(
new Date()) + String.format(Locale.getDefault(),
" %f %f %f %f\n",
location.getLatitude(),
location.getLongitude(),
location.getAltitude(),
location.getBearing());
outputStreamWriter.write(line.getBytes());
outputStreamWriter.flush();
outputStreamWriter.close();
}
catch (Throwable e) {
Log.e("Exception", "File write failed: " + e.getMessage());
}
}
I really haven't got why this code works while the previous wasn't ... maybe one of the reason is openFileOutput() call I was using in the first sample or maybe is the Environment.DIRECTORY_DOCUMENTS I'm using now. What's certain that even if now the file is availabe its availability is not immediate but may require a variable timespan (from some seconds to some minutes).
May this code be of any help to someonelse.

Related

Android saving a docx file

I want to save text from my app that can be opened from various devices (phones, tablets, computers, ect) and after doing research I figured a docx would be the best choice. I need to have the text be monospaced so a simple .txt file would not work. I noticed though that when I save this file and try to open it up using QuickOffice or POLARIS or any other office type application on my phone or tablet I get a message "Unsupported file". I can open it in office using my computer but I get a message saying that I need to select an encoding. Is there a way in my program either by setting the fontFamily or something similar to remedy this?
I'm under the assumption that it is saving using whatever the default font is for Android and that font doesn't exist in these other applications so it does not recognize it. But I could be wrong. Any help would be appreciated! This is my code for saving: (I should note that string1(2)(3) come from a TextView
private void saveResults() {
SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss", Locale.getDefault());
String timeStamp = format.format(new Date());
String filename = timeStamp + "_Results.docx";
CharSequence fileOutput = "Results:\n" + string1 + "\n" + string2 + "\n\n" +
string3;
if(isExternalStorageWritable()){
try{
File file = new File(Environment.getExternalStorageDirectory(), filename);
file.createNewFile();
FileOutputStream fileOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fileOut);
myOutWriter.append(fileOutput);
myOutWriter.close();
fileOut.close();
Toast.makeText(getBaseContext(),
"Saved " + filename + " to " + Environment.getExternalStorageDirectory(),
Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(getBaseContext(), "Cannot write to external storage", Toast.LENGTH_SHORT).show();
}
}

Android - Cannot share vCard from internal cache

I am using a ShareActionProvider to share a vcf file I created.
If I store the file in the external cache, I have absolutely no problems sharing the file, but if I store it in the internal cache, every app I try to share the vCard with says the file is corrupted or unsupported.
I read the file after creating it, and in both cases they are exactly the same.
This code works:
File dir = new File(getExternalCacheDir() + "/contact");
dir.mkdirs();
vcfFile = new File(dir, name.replace(' ', '+') + ".vcf");
However, if I use getCacheDir() instead, I get the problem.
Here's the code for creating the file:
FileWriter fw;
try {
fw = new FileWriter(vcfFile);
fw.write("BEGIN:VCARD\r\n");
fw.write("VERSION:2.1\r\n");
fw.write("N:" + codedName + "\r\n");
fw.write("FN:" + name + "\r\n");
fw.write("ORG:" + org + "\r\n");
fw.write("TITLE:" + position + "\r\n");
fw.write("TEL;PREF;WORK;VOICE;ENCODING=QUOTED-PRINTABLE:" + phone + "\r\n");
fw.write("TEL;PREF;WORK;FAX;ENCODING=QUOTED-PRINTABLE:" + fax + "\r\n");
fw.write("ADR;WORK;;ENCODING=QUOTED-PRINTABLE:" + codedAddr + "\r\n");
fw.write("EMAIL;INTERNET:" + email + "\r\n");
fw.write("URL;WORK:" + website + "\r\n");
fw.write("PHOTO;TYPE=JPEG;ENCODING=BASE64:" + codedImage + "\r\n");
fw.write("END:VCARD\r\n");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
And here's the code for the ShareActionProvider:
provider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
if (provider != null) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/vcard");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(vcfFile));
provider.setShareIntent(intent);
}
Any ideas of what I'm doing wrong?
Any ideas of what I'm doing wrong?
every app I try to share the vCard with says the file is corrupted or unsupported.
According with Using the Internal Storage
You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user)...
For this reason, it is advisable to use External Storage
Manifest
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Code
```
public void sharePublicContact(View view){
String name = "Mickey Mouse";
String org = "Disney Corp.";
String note = "";
File dir = new File(getExternalCacheDir() + "/contact");
dir.mkdirs();
File vcfFile = new File(dir, name.replace(' ', '+') + ".vcf");
FileWriter fw;
try {
fw = new FileWriter(vcfFile);
fw.write("BEGIN:VCARD\r\n");
fw.write("VERSION:3.0\r\n");
fw.write("FN:" + name + "\r\n");
fw.write("ORG:" + org + "\r\n");
fw.write("NOTE:" + note + "\r\n");
fw.write("END:VCARD\r\n");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/vcard");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(vcfFile));
startActivity(sendIntent);
}
```

context.openFileInput() returning null when trying to access a stored file

Currently, I have the following code for saving a Web Archive and then getting it as a FileInputStream. However, the channel within webContent remains null and a FileNotFoundException is thrown:
// Save the Web Archive once loading is finished
String path = context.getFilesDir().getAbsolutePath()
+ File.separator + WEB_PREFIX + postId;
webView.saveWebArchive(path);
FileInputStream webContent = null;
try {
webContent = context.openFileInput(WEB_PREFIX + postId);
} catch (FileNotFoundException e) {
Log.d("onPageFinished()", "FileNotFoundException");
e.printStackTrace();
}
If I try to perform context.openFileInput(path) instead, I get
09-05 23:39:42.448: E/AndroidRuntime(8399): java.lang.IllegalArgumentException: File /data/data/com.example/files/web-2189241737372651547 contains a path separator
Does anyone know of a solution? The file certainly exists, since I saved it in the previous line.
openFileInput() doesn't accept paths, only a file name if you want to access a path.
Use this instead:
File file = new File(this.getFilesDir().getAbsolutePath() + (WEB_PREFIX + postId));
EDIT:
You need to make sure you are saving and retrieving the file from the same place. Give this a go:
Note: I'm not sure you need File.separator but try with and without it and see which one works.
String path = context.getFilesDir().getAbsolutePath()
+ File.separator + WEB_PREFIX + postId;
webView.saveWebArchive(path);
FileInputStream webContent = null;
try {
webContent = new File(path);
} catch (FileNotFoundException e) {
Log.d("onPageFinished()", "FileNotFoundException");
e.printStackTrace();
}

How to log only from my process onto a single log file

I have 3 different process running and wanted to collect logs from them on to a single log file, using logcat.
Is it possible this logfile to have logs only from my 3 processes ? How to do the same programitcally.
any help regarding the same highly appreciated.
-regards,
Manju
you can try this way call this method and put put your message what you write in log file and is stored in your sd card. Any where your application tested it will create a log and you can see the details
public static void MyLog(String msg_location, String log_message) {
String messgae_location = msg_location;
String message_details = log_message;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath()
+ "/mydata/LOG");
if (!dir.exists()) {
dir.mkdirs();
}
BufferedWriter bufferedWritter = null;
try {
bufferedWritter = new BufferedWriter(new FileWriter(dir
+ File.separator + "my_Log.txt", true));
String logString = null;
logString = currentDateTime1() + ": " + messgae_location + ": "
+ message_details + "\n";
bufferedWritter.write(logString);
bufferedWritter.newLine();
bufferedWritter.flush();
} catch (FileNotFoundException e) {
// e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
}
}
You can filter the logcat output by tags.
You can use regular expressions when filtering. E.g. if you have 3 tags tag1m tag2, tag3 then if your filter is tag1|tag2 you will see logcaat output tagged by tag1 and tag2 (but not tag3).
To log your messages in a file better use Log4j for android. It's also simple.

Camera SetPreviewCallback best way to convert YUV to RGB

I am using this code to write an image to SD after camera.takePicture is called:
protected String doInBackground(byte[]... jpeg) {
File directory=new File(Environment.getExternalStorageDirectory() + "/" + getString(R.string.qpw_picture_path) + "/" + getString(R.string.qpw_picture_title) + "_" + initialTime);
directory.mkdirs();
String currentTime = new SimpleDateFormat(getString(R.string.qpw_date_format)).format(new Date());
File photo = new File (directory, getString(R.string.qpw_picture_title) + "_" + currentTime + "_" + current + ".jpg");
current++;
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos=new FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.flush();
fos.close();
}
catch (java.io.IOException e) {
}
new ImageMediaScanner(getBaseContext(), photo);
return(null);
}
Which is working fine in this case, but when I am using the same code to write images from camera.setPreviewCallback, I end up with 450KB corrupted images on SD which cannot be used or even opened.
Any help or advice would be appreciated.
Edit:
It seems that data should be first converted from YUV to RGB before saving. Having tried one of the many code samples found on Google and SO, I was facing no more issues.
Does anyone know what is the best way of doing it? In terms of speed, memory allocation, CPU...
Just in case someone stumbles on the same issue this SO post summarize well what I was looking for.

Categories

Resources