Android: Intentionally Blank Lines in EditText Are Not Getting Saved

469 views Asked by At

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

There are 1 answers

1
LogicOwl On

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