Login     Sign Up
Cyril Sermon (@admin)
10 months ago

In this chapter, you’ll be introduced to three of the most versatile data persistence techniques in Android — preferences, local files, and SQLite databases — before looking at Content Providers.

Saving and loading data is an essential requirement for most applications. At a minimum, Activities should save their User Interface (UI) state each time they move out of the foreground. This ensures that the same UI state is presented when it’s next seen, even if the process has been killed and restarted before that happens.

It’s also likely that you’ll need to save preferences, to let users customize the application, and per-sist data entered or recorded. Just as important is the ability to load data from files, databases, and Content Providers — your own, and those shared by native and third-party applications.

Android’s nondeterministic Activity and Application lifetimes make persisting UI state and application data between sessions particularly important. Android offers several alternatives for saving application data, each optimized to fulfill a particular need.

Preferences are a simple, lightweight key/value pair mechanism for saving primitive application data, most commonly a user’s application preferences. Android also provides access to the local filesystem, both through specialized methods and the normal Java.IO classes.

For a more robust persistence layer, Android provides the SQLite database library. The SQLite database offers a powerful native SQL database over which you have total control.

Content Providers offer a generic interface to any data source. They effectively decouple the underlying data storage technique from the application layer.

By default, access to all files, databases, and preferences is restricted to the application that created them. Content Providers offer a managed way for your applications to share private data with other applications. As a result, your applications can use the Content Providers offered by others, including native providers.