Android Development

Google's android guide Home Contact

    Shared Preferences

    Storing data in Android apps is essential for various reasons, such as maintaining user preferences, saving app settings, caching data for offline use, , storing user-generated content etc. One common method for storing small amounts of user-specific data is through SharedPreferences. Some of its key features include:

  • The Shared Preferences APIs provide a convenient way to save and retrieve primitive Key-Value pairs, typically for small application data such as settings, user authentication etc.
  • The stored data persists and can be deleted either upon application uninstallation or by explicitly deleting Shared Preferences data using specific methods provided by the Shared Preferences APIs.
  • The data stored can consist of various types, including booleans, floats, integers, longs, and strings. It is also possible to store Java objects by converting them to JSON strings using the GSON library.
  • To access the stored data, view the application folder on the device or use the File Explorer on an emulator. The data is stored as an XML file located at: /data/data/APP_PACKAGE/shared_prefs/.
  • To ensure persistent data storage, it is commonly (but not always!) saved in the onPause() method, which is called when an activity is no longer in the foreground and about to loose focus. Restore where needed in the onCreate() method of the activity.

    Storing values

  • Create an instance of the SharedPreferences class by calling the getSharedPreferences() method, passing in a name for the SharedPreferences file and a mode. The name is a unique identifier for the SharedPreferences file, and the mode determines the accessibility and visibility of the file.
  • Obtain an instance of the SharedPreferences.Editor class by calling the edit() method on the SharedPreferences object. The Editor class provides methods to modify the SharedPreferences data.
  • Use the methods provided by the Editor class to make changes to the SharedPreferences data. For example, use methods like putString(), putInt(), putBoolean(), etc., to store values of different types.
  • Use apply() to save the changes asynchronously in the background or use commit() to save the changes synchronously and get a boolean result indicating the success of the operation.

    Retrieving stored values

  • Use the appropriate getter methods based on the type of value you want to retrieve
  • For a string it will be 'getString()' , for integer 'getInteger()', for long 'getLong()', and for all values 'getAll()' etc.

When to used Shared Preference

SharedPreferences are suitable for small amounts of data, such as preferences and settings. For more complex or larger datasets, use other other storage mechanisms like databases or file storage. The choice of storage mechanism depends on the type of data which needs to be storeed, app's requirements, and the trade-offs between simplicity, performance, and data management.

Data Security is an important consideration for any data stored using SharedPreferences. Proper encryption should be provided,to make the xml file holding data un-readable, for unauthorized persons.

  • An example code for encrypting data stored on shared preferences XML file in the DATA/data/{application package} directory:

    SharedPreferences Data Security

Note:

With the arrival of JetPack there is new alternative to Shared Preferences, in form of Preferences DataStore. It tries to address some drawbacks with shared preferences, such as use of synchronous API, lack of signaling errors (IOException etc) and lack of transactional API. It uses Kotlin flow, allowing it to be used as LiveData, for coroutines, and more suitable option when using JetPack. While Shared Preference staus as reliable and easy-use mechanism, but DataStore API has advantage over it for certain use cases, specifically when working with Jetpack components and using modern Android development techniques.

Shared Preference Example


// Get an instance of SharedPreferences
SharedPreferences preferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);


// Write a value to SharedPreferences
SharedPreferences.Editor editor = preferences.edit();
editor.putString("key", "value");
editor.apply();

// Read a value from SharedPreferences (for string here)
String value = preferences.getString("key", "default_value");




The default value in SharedPreferences acts as a fallback value that is returned when the requested key doesn't have an associated value in the SharedPreferences file i.e it has not been set before. This prevents unexpected null values. If the preference with the key "key" exists in the preferences object, the corresponding value will be returned, otherwise, the string "default_value" or whatever string is used as default value.

Context.MODE_PRIVATE makes it accessible only within the application providing data security and privacy. For sharing data between applications, use Content Provider or FileProvider.