The capability to have data that the app uses or relies on to continue to be available regardless of changes to the app’s state as it moves through the app life cycle is vital to the user experience with the app—and for the app itself to be a useful tool. For this to occur, the data needs to persist through these life cycle changes. Android provides several ways in which the developer can make data persist. This chapter introduces you to three of these data persistence approaches.
A significant amount of time will be spent on understanding and using the SQLite database system incorporated with Android, but the chapter also discusses storing data in files and demonstrates how to store individual pieces of data in an object that persists across an app’s life cycle. Preferences, Files, and Database the three approaches to data persistence discussed in this chapter are Shared Preferences, standard flat file input/output, and the SQLite database system.
Each of these approaches provides capabilities that are relevant for different tasks in an app. shared Preferences are often used for a limited set of data that represent user choices about the way they want the app configured. They may also be used for other data that needs to persist across life cycle changes. Flat files are useful for backing up data and transmitting to other users.
Finally, databases are the workhorses for data manipulation, storage, and retrieval. Developing an understanding of where, when, and how to use these data persistence approaches is very important to effective development of an Android app. Preferences are implemented through use of the shared Preferences class.
A shared Preferences object can be used to store primitive data (for example, integers and strings) in a key/value pair. Each value has its own key for storage and retrieval of that data. shared Preferences are stored in memory private to the app and will persist as long as the app remains installed on the device. App upgrades will not impact the values stored with Shared Preferences.