Today we are going to code about a sample app with some operations I usually play with text files in my Android applications. These operations would include creating, reading, updating,and deleting text files. I find these operations really useful when I have to store some data temporarily, creating some log files, or store some actual content just like what evernote does, see screenshot below.
|Click to enlarge. content.enml is basically a text/xml file.|
For apps like Evernote, storing some user content data on the device disk or sdcard is okay, some reason include, the device is a personal property, it is always with you. Another reason is, the data is "syncable". If you think you lost some data in the device (like accidental file deletion), you can always simply sync and your data will come back to life in your device. I love cloud computing!
Below is the code download, basic CRUD codes and a Sample Application.
|Click to enlarge.|
In this sample application, when a user clicked a button:
- Create Text File - a folder in your sdcard will be created with an empty text file in it (sdcard/MikeDalisayFolder/coan_log_file.txt)
- Read Text File - the contents of coan_log_file.txt text file will be shown in the screen, you should click the update text file button first so it will have contents.
- Update Text File - it will update our text file with two lines of text.
- Delete Text File - it will delete our text file, of course. :)
We will use a TextFileHelper class I created. I believe you can see more useful techniques here like code re-usability and validation.
src/com.your.package/TextFileHelper.java code - This class contains our text file CRUD codes.
AndroidManifest.xml code - the permission will be WRITE_EXTERNAL_STORAGE
Some other notes:
- You can create a text file with a different extension name and yet it will still be readable by your program. For example, you can make a file name like "my_file.coan", evernote does "content.enml". That file will not be easily read in the device since there are no app that can open a file with that extension. Your text file will be easily ignored by the users.
- If you want to update a specific line of your text file, you have to read it first, track the line number, insert the updated line and use the code above.
For FREE programming tutorials, click the red button below and subscribe! :)