Shared Preferences In Android


Android provides several options for us to save persistent application data. The solution us choose depends on our specific needs, such as whether the data should be private to our application or accessible to other applications (and the user) and how much space our data requires.

User data storage options are the following:

  • Shared Preferences
    • Store private primitive data in key-value pairs.
  • Internal Storage
  • External Storage
  • SQLite Databases

Shared Preferences

Preferences are an important part of an Android application. It is important to let the users have the choice to modify and personalize their application depending on their needs.

The SharedPreferences class provides a general framework that allows us to save and retrieve persistent key-value pairs of primitive data types. We can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist  across user sessions (even if our application is killed).

The main importance of preferences is even we comes out the application, the preferences available even for next start of the application also.

To get a SharedPreferences object for user application, use one of two methods:

  • getSharedPreferences()
    • Use this if we need multiple preferences files identified by name, which we specify with the first parameter.
  • getPreferences()
    • Use this if we need only one preferences file for our Activity. Because this will be the only preferences file for our Activity, we no need to supply a name.

To write values:

  1. Call edit() to get a SharedPreferences.Editor.
  2. Add values with methods such as putBoolean() and putString().
  3. Commit the new values with commit()

To read values, use SharedPreferences methods such as getBoolean() and getString().





qq qqq

Leave a Reply