Android saving a docx file - android

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

Related

Writing data to a public text file in 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.

When accessing a text file on my android device through my PC, part of it doesn't come through

In my android app, I am putting values to a text file and I have confirmed that it works. I can open the text file on my android device and see ALL of the data in there as it should be. However, when I plug the device into my PC via USB, some of the data in the text file gets cut off.
Here's the data I see on my android device when I open the text file:
false,false,false,NULL,NULL,false,false,NULL,NULL,60,67,false,true,1,false,4,1,
Here's the data I see when I access the text file on my computer:
false,false,false,NULL,NULL,false,false,NULL,NULL,60,67,false,true,1,f
As you can see, the last few pieces of data get cut off. I've tried with different data and it still gets cut off there.
I'm not sure if this will help as the following code seemingly does get all the data to the text file (if looking on my android device), but here's the code for writing to the text file. I'm getting two lists of data from SharedPreferences files I've previously created and writing them to a file when a button is pressed.
SharedPreferences auto = getSharedPreferences("Auto", MODE_PRIVATE);
SharedPreferences teleop = getSharedPreferences("Teleop", MODE_PRIVATE);
autoValues = auto.getAll();
teleopValues = teleop.getAll();
public void writeToFile(View view){
try {
FileOutputStream stream = new FileOutputStream(myFile);
for (Map.Entry<String, ?> entry : autoValues.entrySet()){
stream.write(entry.getValue().toString().getBytes());
stream.write(",".getBytes());
}
for (Map.Entry<String, ?> entry : teleopValues.entrySet()){
stream.write(entry.getValue().toString().getBytes());
stream.write(",".getBytes());
}
stream.close();
System.out.println("SUCCESS: MAY HAVE WRITTEN TO FILE IN EXPORT");
} catch (Exception e){
e.printStackTrace();
System.out.println("ERROR: DID NOT WRITE TO FILE");
}
}
Use following function to efficiently write to your file. You must have permission to access external storage.
public static void logToFile(String message) {
String formattedData = String.format("%s", (new SimpleDateFormat("dd-MM HH:mm:ss", Locale.getDefault())
.format(new Date())) + "\t\t\t" + message + "\n");
FileOutputStream stream = null;
String path = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DOWNLOADS;
try {
File file = new File(path + "/Logger.txt");
if (!file.exists()) {
file.createNewFile();
}
stream = new FileOutputStream(file, true);
stream.write(formattedData.getBytes());
} catch (IOException e) {
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.

Create a file locally on android(not on SD card)

I am having an issue where I am trying to create a file locally on the android emulator however when I test it the file exists, it doesn't. I do not have access to a physical android device so am using the emulator.
Please note I do not want to save the file on the SD card. I am not very familiar with android's file structure so forgive me if my code doesn't make sense.
This is the code I am currently using and it doesn't work :(
EditText editText = (EditText) findViewById(R.id.editTextName);
String sName = editText.getText().toString();
editText = (EditText) findViewById(R.id.editTextEmail);
String sEmail = editText.getText().toString();
editText = (EditText) findViewById(R.id.editTextPostal);
String sPostal = editText.getText().toString();
File file = new File("/storage/new/test.txt");
FileOutputStream fos;
byte[] data = new String("Name: " + sName + " Subject: " + sEmail + " Question: " + sPostal ).getBytes();
OutputStream myOutput;
try {
myOutput = new BufferedOutputStream(new FileOutputStream(file,true));
myOutput.write(data);
myOutput.flush();
myOutput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(file.exists())
{
finish();
}
Could anyone experienced enough in the area of android development provide me with some sample code or point me in the right direction so I can get this bad boy working?
EDIT: When I say it doesn't work, I mean the file never gets created.
If you are new to file storage in Android I suggest you read trough this piece of documentation to get started - it should answer your questions with examples.

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