{"id":147,"date":"2014-05-26T07:17:51","date_gmt":"2014-05-26T11:17:51","guid":{"rendered":"https:\/\/cindypotvin.com\/?p=147"},"modified":"2017-06-03T11:04:51","modified_gmt":"2017-06-03T15:04:51","slug":"saving-data-to-a-file-in-your-android-application","status":"publish","type":"post","link":"https:\/\/cindypotvin.com\/saving-data-to-a-file-in-your-android-application\/","title":{"rendered":"Saving data to a file in your Android application"},"content":{"rendered":"

This is the second post in my series about storage in Android applications. The other post is available here :<\/p>\n

https:\/\/cindypotvin.com\/introduction-how-to-save-data-in-your-android-application\/<\/a><\/p>\n

This post is about saving to a file from an Android application, which is the easiest way to store data. There are many situations where you may need to save a file : you may want to use an existing file format to create files that can be opened by the user in another application or the data is simple enough that it can be represented by a text file or a format like XML or YAML. For complex data a database may be a better option, since accessing and parsing a large file can be slow and there are no integrity checks unless you code them by hand. On the other hand, there is less overhead and it easier to work with files than debugging with the data in a database. Depending on how the user will interact (or not) with your files, you will need to decide first which kind of storage to use.<\/p>\n

Internal storage<\/h2>\n

Each application has its own private internal storage to save files. This is the kind of storage to use if the user shouldn’t be able to modify the file from outside your application, and if other application shouldn’t be able to access those files. Since the internal storage is private to your application, the files will be deleted if your application is uninstalled. The internal storage is also where your application is installed by default, so your files will always be available. On some older or cheaper devices the internal storage is quite limited, so you need to be careful about the size of the data you save if you need to support those devices.<\/p>\n

You should never hardcode the path to the storage directories, since the directory may changes depending on the version of the Android OS used.\u00a0 Also, Android 4.4 introduces the concept of multiple users : in that case, the internal and external storage depend on the user logged in and the files of the other users will be invisible. Here are some of the methods used to get the paths to the internal storage:<\/p>\n