Don’t use Android Shared Preferences

Shared Preference

Shared Preferences is one of the most interesting data storage option Android provides its users. Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage. It can be thought of as a dictionary or a key/value pair. Shared Preferences is suitable in different situations.

  • Persist Data across user sessions, even if app is killed and restarted, or device is rebooted.
  • Data that should be remembered across sessions, such as user’s preferred settings or their game score.
  • Common use is to store user preferences

So it is common to use shared preferences in most of the Android applications that you develop. For each of them, you’ll have to write lot boilerplate code to manage these Shared Preferences file. In this article, I’m gonna introduce you to an Open-Source library – Android Simple Preference Manager, that can take care of all operations on Android Shared Preference, so that you can utilize your time for something else rather than write these boilerplate code.

Overview

Android Simple Preference Manager

Android Simple Preference Manager is a lightweight android library that can assist you with Android Shared Preferences. Some of the features of Android Simple Preference Manager are

  • Provides a default Shared Preference to get started right away.
  • Store and retrieve custom objects to and from a Shared Preference file.
  • Store and retrieve String, Boolean, Integer, Float, Long and String Sets to and from a Shared Preference file.
  • Store a Map of information as individual key value pairs in Shared Preferences.
  • Check whether data exists in Shared Preference file.
  • Remove individual and all data from a Shared Preference file.
  • Open Shared Preference file with custom names.
  • Open a shared preference file in different operation modes.

How to integrate in your App

Integrating the Android Simple Preference Manager into you app is extremely easy. A few changes in the build gradle and your all ready to use Simple Preference Manager.

  • Add the JitPack repository to your build file. Add it in your project / root build.gradle at the end of repositories
allprojects {
  repositories {
    ...
    maven { url "https://jitpack.io" }
  }
}
  • Add the Simple Preference Manager dependency to your module / app build.gradle in the dependencies section
dependencies {
        implementation 'com.github.a-anand-91119:Android-Simple-Preference-Manager:<latest-version>'
}

Once you have integrated the library in your project, you can start using it right away. The different options and how to use them are explained below.

Use Default Shared Preference

Simple Preference Manager comes out of the box with a default preference file that you can use. First create an instance of SimplePreferenceManager that uses this Default Shared Preference.

// Using Default SharedPreferences
// Create an instance of SimplePreferenceManager using SimplePreferenceManagerBuilder
SimplePreferenceManager preferenceManager = new SimplePreferenceManager.SimplePreferenceManagerBuilder(this)
                  .build();

When you create an instance of SimplePreferenceManager as shown above, you’ll be using the Default SharedPreference in Private Mode. (Context.MODE_PRIVATE)

Saving and Retrieving Data

SimplePreferenceManager provides methods using which you can save and retrieve data from a Shared Preference file. The save method return a boolean value indicating whether the data was saved successfully or not. The methods provided are

  • Save Data
    • boolean saveString(String key, String value)
    • boolean saveInteger(String key, Integer value)
    • boolean saveLong(String key, Long value)
    • boolean saveFloat(String key, Float value)
    • boolean saveBoolean(String key, Boolean value)
    • boolean saveStringSet(String key, Set<String> value)
  • Retrieve Data
    • String fetchString(String key)
    • Integer fetchInteger(String key)
    • Long fetchLong(String key)
    • Float fetchFloat(String key)
    • Boolean fetchBoolean(String key)
    • Set<String> fetchStringSet(String key)

If a fetch call is made using a key that is not present in Shared Preference file, then corresponding default value will be returned.

// Saving Data To Shared Preferences
preferenceManager.saveString("Key_1", "Value");
preferenceManager.saveLong("Key_2", (long) 100);
preferenceManager.saveFloat("Key_3", (float) 1000.1);
preferenceManager.saveInteger("Key_4", 10);
preferenceManager.saveBoolean("Key_5", true);

// Retrieving Data From Shared Preferences
String s = preferenceManager.fetchString("Key_1");
Long l = preferenceManager.fetchLong("Key_2");
Float f = preferenceManager.fetchFloat("Key_3");
Integer i = preferenceManager.fetchInteger("Key_4");
Boolean b = preferenceManager.fetchBoolean("Key_5");

Enable Object Storage Support

SimplePreferenceManager is also capable of storing and retrieving object data from a shared preference file as long as the objects are Serializable. Object Support is optional and must be enabled while creating the SimplePermissionManager.

// Saving and Retrieving Objects
// Enabling Object Support Using Builder
SimplePreferenceManager preferenceManager = new SimplePreferenceManager.SimplePreferenceManagerBuilder(this)
                .withObjectStorageSupport()
                .build();

Now lets see how to save and fetch objects from shared preference file.

// Save Objects
preferenceManager.saveObject("Key_6", new CustomObject("data", "99"));
// Retrieving Objects
(CustomObject)preferenceManager.fetchObject("Key_6", CustomObject.class);

Saving Bulk Data

Simple Preference Manager supports storing bulk data into Shared Preferences. To do so, pass the data as a Map to the putAll() method. The possible data inputs are

  • putAll(Map<String, String>)
  • putAll(Map<String, Integer>)
  • putAll(Map<String, Float>)
  • putAll(Map<String, Long>)
  • putAll(Map<String, Boolean>)
  • putAll(Map<String, Set<String>>)
  • putAll(Map<String, <? extends Serializable>>) [Custom Serializable Objects]
// Saving Map of Key-Value Pairs
Map<String, Float> floatMap = new HashMap<>();
floatMap.put("ONE_F", 1f);
floatMap.put("TWO_F", 2f);
floatMap.put("THREE_F", 3f);
preferenceManager.putAll(floatMap);
// Retrieve the data
Float f = preferenceManager.fetchFloat("ONE_F");

Additional Options

Simple Preference Manager allows you to specify names to your Shared Preference files and also to specify the operation modes. You can specify then while create the instance.

Shared Preference with Custom Name

// Create SharedPreference File With Custom Names
SimplePreferenceManager preferenceManager = new SimplePreferenceManager.SimplePreferenceManagerBuilder(this)
                .havingFileName("CustomFileName")
                .build();

Shared Preference on different operating mode

// Specifying the Operation Mode
SimplePreferenceManager preferenceManager = new SimplePreferenceManager.SimplePreferenceManagerBuilder(this)
                .usingOperationMode(Context.MODE_PRIVATE)
                .build();

Or you can combine both

// Specifying the Operation Mode
SimplePreferenceManager preferenceManager = new SimplePreferenceManager.SimplePreferenceManagerBuilder(this)
                .havingFileName("CustomFileName")
                .usingOperationMode(Context.MODE_PRIVATE)
                .build();

Simple Preference Manager provides methods to check whether data exists in a shared preference file or not, remove a particular entry from a Shared Preference file, or to clear the entire data.

// Additional Options
// Remove all data from Shared Preference File
preferenceManager.removeAll();

// Remove particular Key-Value Pair from Shared Preferences
preferenceManager.removeData("KEY");

// check whether Shared Preference contains particular key
Boolean contains = preferenceManager.contains("KEY");

Contribute

You can also contribute to this library to add new features or fix any bugs that you find. Create a pull request with the changes and it will be merged after reviewing. You can check out some of my other articles

If you have any doubt’s or questions, please feel free to ask in the comment section and I’ll be happy to help.

One thought on “Don’t use Android Shared Preferences

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top