20.08.2016 Views

Professional Android 4 Application Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

7Files, Saving State,<br />

and Preferences<br />

WHAT’S IN THIS CHAPTER?<br />

‰ Persisting simple application data using Shared Preferences<br />

‰ Saving Activity instance data between sessions<br />

‰ Managing application preferences and building Preference Screens<br />

‰ Saving and loading files and managing the local filesystem<br />

‰ Including static files as external resources<br />

This chapter introduces some of the simplest and most versatile data-persistence techniques in<br />

<strong>Android</strong>: Shared Preferences, instance-state Bundles, and local files.<br />

Saving and loading data is essential for most applications. At a minimum, an Activity should<br />

save its user interface (UI) state before it becomes inactive to ensure the same UI is presented<br />

when it restarts. It’s also likely that you’ll need to save user preferences and UI selections.<br />

<strong>Android</strong>’s nondeterministic Activity and application lifetimes make persisting UI state and<br />

application data between sessions particularly important, as your application process may<br />

have been killed and restarted before it returns to the foreground. <strong>Android</strong> offers several alternatives<br />

for saving application data, each optimized to fulfill a particular need.<br />

Shared Preferences are a simple, lightweight name/value pair (NVP) mechanism for saving<br />

primitive application data, most commonly a user’s application preferences. <strong>Android</strong> also<br />

offers a mechanism for recording application state within the Activity lifecycle handlers, as<br />

well as for providing access to the local filesystem, through both specialized methods and the<br />

java.io classes.<br />

<strong>Android</strong> also offers a rich framework for user preferences, allowing you to create settings<br />

screens consistent with the system settings.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!