In the app that I'm making, my goal for it is to be a quick and easy notes/documents app. However, a problem that I have is that when the user saves the text they enter into an EditText, if there are extra lines that they put in, for basic formatting, those lines don't get saved into the text file. How could I remedy this? Here's the code for the saving process. Thanks!
String itemName = fileSaveListView.getItemAtPosition(position).toString();
File myExistingFile = new File(savedFilesDir, itemName);
if (myExistingFile.exists()){
myExistingFile.mkdirs();
}
try {
FileOutputStream fosForExistingFiles = new FileOutputStream(myExistingFile);
OutputStreamWriter myOutWriterExistingFiles = new OutputStreamWriter(fosForExistingFiles);
myOutWriterExistingFiles.append(textEntryEditText.getEditableText().toString());
myOutWriterExistingFiles.close();
fosForExistingFiles.close();
Toast.makeText(getBaseContext(), "Finished writing " + itemName + " to the folder", Toast.LENGTH_SHORT).show();
final AlertDialog thefileSaver = fileSaver.create();
thefileSaver.dismiss();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
OK, I finally figured it out, and got it working. For anyone else that is having this problem, here's what you need to do. When grabbing the text from your EditText, convert it to Html with the Html.toHtml function, like below.
myOutWriter.append(Html.toHtml(textEntryEditText.getText()));
Now, your text file will be saved WITH any linebreaks you have entered. The next thing to do, if you wish to display your saved file in the EditText, you just need to convert back from Html. Like so.
textEntryEditText.setText(Html.fromHtml(String.valueOf(<your file reader>)));
I have been trying to fix this problem for a VERY long time, so if anyone else was suffering like I was, I hope this helps you! :D
Related
I just started to learn developping android and I have a (probably) basic questions, but I didn't find anything clear.
I'm trying to store data in a JSON file, well, I've understood the logic to store it, my way is:
public boolean writeFileJson(JSONObject jobj) {
try {
FileOutputStream fOut = openFileOutput(file, Context.MODE_PRIVATE);
fOut.write(jobj.toString().getBytes());
fOut.close();
Toast.makeText(getBaseContext(), "file saved", Toast.LENGTH_SHORT).show();
} catch (Exception e1) {
e1.printStackTrace();
}
return true;
}
But my problem is to read, and concretely for the first time, because the way I do it is:
public String readFileJson() {
int c;
String temp = "";
try {
FileInputStream fin = openFileInput(file);
while ((c = fin.read()) != -1) {
temp = temp + Character.toString((char) c);
}
Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
} catch (Exception e2) {
}
return temp;
}
So wen I read it for the first time and I want to acces to a parameter of my JSON is obvious that any JSON Object already exist in the file.
So I try to save a first JSON Object with my parameters in onCreate() method and save it in the file, but wen I run the app, and I stop it, it returns again to execute onCreate() and deletes all data stored during the run time.
So my question is: There is any way to init only for one time the parameters of the JSON file to could access for the first time unlike it's empty???
I hope that I'd explained well!!
Thanxxxx!!!!
You can create your own flag boolean and check when you start.
Well I don't understand well why you can use a flag if the flag is set to init value in onCreate(), but I've tried a basic method: check each time if the json file is null. But it's like so basic no? Is there any ther way, or trying to understand how to use flags without reset their values?
msgjson = readFileJson();
if(msgjson == "") {
json.put("ARRAY", jsonArray);
}else{
json = new JSONObject(msgjson);
}
Thanx!!
I confess I'm a bit stumped on this one. I've just started with Android programming and am loving the experience so far, but I've got a mysterious problem where I write to files but they remain indefinitely empty (no, I'm pretty sure I'm not overwriting them accidentally).
The scenario is that I'd like to record a few seconds of sensor data to a log file on the SD card upon hitting a button. I also display the same content to the screen. However, though the content that appears on the screen is correct, the log file gets created but is empty.
I can only assume that it has something to do with the fact that I'm calling write from the onSensorChanged(Event) method, since the same code executes just fine when used elsewhere.
public MyClass(....){
....
sensorManager.registerListener(this, accelerometer, sensorManager.SENSOR_DELAY_NORMAL);
Thread.sleep(time * 1000);
sensorManager.unregisterListener(this);
try {
logWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onSensorChanged(SensorEvent event){
String msg = msgFor(event);
try {
logWriter.write("SOME_TEXT" + msg + "\n"); // FileWriter logWriter is a field, but the file is empty in the end
} catch (IOException e){
e.printStackTrace();
}
resultBox.append("\n" + msg); // TextView resultBox is a field, and writes to screen correctly
Log.d("SENSOR-CHANGE", msg);
}
private String msgFor(SensorEvent event){
return event.timestamp+", "+event.sensor.getName()+", "+Arrays.toString(event.values);
}
Any advice would be greatly appreciated! I am aware that there are some similar threads out there, but I didn't find exactly what I needed.
I am developing an App in which I need to lock screen than if user unlocks, it should ask for password...
Help would be really appreciated.
What you basically need is a way to make sure that the user has a password set for their lock screen. There's no clean way of doing this. No formal API. If you're willing to risk a hack, you can try this. I cobbled it together some code I found on this site.
boolean hasPasswordOnLockScreen(){
String sLockPasswordFilename =
android.os.Environment.getDataDirectory().getAbsolutePath() +
"/system/password.key";
try {
// Check if we can read a byte from the file
RandomAccessFile raf = new RandomAccessFile(filename, "r");
raf.readByte();
raf.close();
return true;
} catch (FileNotFoundException fnfe) {
return false;
} catch (IOException ioe) {
return false;
}
}
Note that this is a hack and has the potential to not work in the future is the path and file name of the password file changes.
my history objects only have 2 fields (id + name). i have to save them. i used sharedpreferences because this is just perfect to save key-value pairs. problem is..there is no possibilty to change to location where the files are saved. i dont want to save them into the sharedpref folder because i want to give the user of the app the possibility to delete all history entries. i have to check which files are history files and which files are preferences files used by the app. this is no proble..but dirty imo. on the other hand..my history files shouldnt be in sharedpref folder..they have nothing to do in that folder..
the other possibility is to store the data in internal storage as xml for example. i would have to write a serializer and parser.
the third possibility (i just remembered writing this question)is to save it via Java Properties. this is probably the easiest solution. its like sharedpref
the last possibility is to store it in sqlite. i dont know..my data is so tiny..and i use a databae to store it?
my question is simply..what do u recommend to use and why. what do you use? same question belongs to the autocomplete values. id like to save the values the user once entered in a textfield. where to save them? where do you save such data?
thx in advance
You can create a separate sharedpreferences file for your history using (say) Context.getSharedPreferences("history") which will create a sharedpreferences file as follows.
/data/data/com.your.package.name/shared_prefs/history.xml
But I'm pretty sure that all sharedpreferences files will be created in /data/data/com.your.package.name/shared_prefs/. I don't think you can change the location.
I may be mis-interpreting your objective but for something like this I would just straight-up use a BufferedWriter from java.io.BufferedWriter to write a new file for each object. Likewise you can read the data with a BufferedReader. The code would look something like this:
public static void save(FileIO files){
BufferedWriter out = null;
try{
//use a writer to make a file named after the object
out = new BufferedWriter(new OutputStreamWriter(
files.writeFile(objectSomething)));
//the first line would be ID
out.write(Integer.toString(objectID));
//second line would be the name
out.write(objectName)
//Theres two possible IOexceptions,
//one for using the writer
//and one for closing the writer
} catch (IOException e) {
} finally {try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this example, I have used "objectSomething" as the string name of the file, objectID and objectName are the int and string respectively that your file contains.
to read this data, pretty straightforward:
public static void load(FileIO files) {
BufferedReader in = null;
try {
// Reads file called ObjectSomething
in = new BufferedReader(new InputStreamReader(
files.readFile(ObjectSomething)));
// Loads values from the file one line at a time
varID = Integer.parseInt(in.readLine());
varName = in.readLine();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
}
here, I've used varID and varName as local variables in this class that you would use if you needed them in your code throughout your application.
Following suggestions on this site, I have adopted SimpleXML from org.simpleframework.xml.
I use this code to deserialize my class from a file on disk:
try {
myPoints = serial.read(Points.class, new File(getFilesDir(), "points.xml"));
Log.i(TAG, "Number of Points: " + myPoints.getSize());
} catch (FileNotFoundException e) {
Log.d(TAG, "No data found!");
} catch (Exception e) {
Log.d(TAG, "Uncaught exception: ", e.getMessage());
}
In the event the contents of file "points.xml" is not legal xml (in my case it's an empty file), serial.read breaks (an exception occurs in Persister.class, sorry I don't have simplexml sources...).
Should I check for xml consistency beforehand?
Can anybody help?
No need to validate before-hand since you won't be able to fix the problem. Just make sure it fails gracefully (as your code appears to be doing).
You may, however, want to see if the file is empty or not in the case of a deserialization error. An empty file is likely not a problem where as a malformed XML file is!