Saving Simple Application Data

The data-persistence techniques in Android provide options for balancing speed, efficiency, and robustness.

> Shared Preferences When storing UI state, user preferences, or application settings, you want a lightweight mechanism to store a known set of values. Shared Preferences let you save groups of key/value pairs of primitive data as named preferences.

> Saved Application State Activities include specialized event handlers to record the current UI state when your application is moved to the background.

> Files It's not pretty, but sometimes writing to and reading from files is the only way to go. Android lets you create and load files on the device's internal or external media.

There are two lightweight techniques for saving simple application data for Android applications — Shared Preferences and a pair of event handlers used for saving Activity instance details. Both mechanisms use a name/value pair (NVP) mechanism to store simple primitive values.

Using the SharedPreferences class you can create named maps of key/value pairs within your application that can be shared among application components running in the same application context.

Shared Preferences support the primitive types Boolean, string, float, long, and integer, making them an ideal means of quickly storing default values, class instance variables, the current UI state, and user preferences. They are most commonly used to persist data across user sessions and to share settings among application components.

Activities also offer the onSaveInstanceState handler. It's designed specifically to persist UI state when the Activity becomes eligible for termination by a resource-hungry run time.

The handler works like the Shared Preference mechanism. It offers a Bundle parameter that represents a key/value map of primitive types that can be used to save the Activity's instance values. This Bundle is then made available as a parameter passed in to the onCreate and onRestoreInstanceState method handlers.

This UI state Bundle should be used to record the values needed for an Activity to present an identical UI when it's displayed after an unexpected close.

Was this article helpful?

0 0
Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


  • mika saisio
    When storing ui state, user preferences, or application settings use a lightweight mechanism?
    8 years ago

Post a comment