Chapter 6

Data Persistence

WHAT YOU WILL LEARN IN THIS CHAPTER

  • How to save simple data using the SharedPreferences object
  • Enabling users to modify preferences using a PreferenceActivity class
  • How to write and read files in internal and external storage
  • Creating and using a SQLite database

In this chapter, you will learn how to persist data in your Android applications. Persisting data is an important topic in application development, as users typically expect to reuse data in the future. For Android, there are primarily three basic ways of persisting data:

  • A lightweight mechanism known as shared preferences to save small chunks of data
  • Traditional file systems
  • A relational database management system through the support of SQLite databases

The techniques discussed in this chapter enable applications to create and access their own private data. In the next chapter you’ll learn how you can share data across applications.

SAVING AND LOADING USER PREFERENCES

Android provides the SharedPreferences object to help you save simple application data. For example, your application may have an option that enables users to specify the font size of the text displayed in your application. In this case, your application needs to remember the size set by the user so that the next time he or she uses the application again, it can set the size appropriately. In order to do so, you have several options. You can save the data to a file, but you have to perform some file management routines, such ...

Get Beginning Android™ 4 Application Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.