Shared Preferences In Android

Learn via video courses
Topics Covered

Overview

Shared Preferences in Android is a mechanism for storing and retrieving key-value pairs of data. It is a lightweight and simple way to store small amounts of user preferences or application settings. Shared Preferences allow developers to persistently store data even after the application is closed or the device is rebooted. It provides methods to store and retrieve data types such as integers, booleans, strings, and floats. Shared Preferences are typically used for storing user preferences, login credentials, app settings, and other small data that needs to be persisted across different app sessions.

Introduction

One of the most frequent challenges in Android programming is permanent data storage and retrieval. There are various methods for doing this, including the use of databases or file storage. Nevertheless, employing a database may be overkill for tiny quantities of data, such as user preferences or settings. Shared Preferences are useful in this situation.

Small quantities of data may be stored and retrieved easily and consistently in Android applications using Shared Preferences. In a nutshell, they are key-value pairs that are kept in a file on the device's internal storage. Even when the program has been stopped or the device has been restarted, the data may always be retrieved.

Shared Preferences are particularly helpful for keeping user preferences or application settings that are not essential to the operation of the program. A program could save the user's preferred language or sound volume setting, for instance. Also used to store login information like usernames and passwords is Shared Preferences.

Importance of Shared Preferences in Android Development

Shared Preferences are a fundamental idea in Android programming, and it provides several advantages that make it a valuable tool for developers. Some of the main advantages of utilizing Shared Preferences are as follows:

  • Persistent Storage : Shared Preferences offer permanent storage for application data. As a result, information is kept on the device's internal storage and is always accessible, even if the program is stopped or the device is restarted.
  • Easy to Use : You may utilize them without creating a database or writing complicated code. Just a few lines of code are needed to add and retrieve key-value pairs after an instance of the SharedPreferences class has been created.
  • Flexibility : Shared Preferences provide some wiggle room. In addition to sets of values, you may store primitive data types like booleans, integers, and strings. Accordingly, you may store any kind of data that your application requires.
  • Secure Data Storage is made possible through Shared Preferences. Other programs on the device cannot access the data that is saved in Shared Preferences since it is private to your application.
  • Shared Preferences are the most effective way to store modest bits of information like user preferences and application settings. They are a useful storage choice because they take up less room on the device.

Types of Shared Preferences

Android development uses two different kinds of shared preferences: default shared preferences and custom shared preferences.

Default Shared Preferences

When an application is installed, Android automatically creates default shared preferences. These preferences are available across the program and are kept in a file called "defaultSharedPreferences". Small quantities of information the program needs, such as the user's chosen language or music preferences, can be stored in the default Shared Preferences.

The getSharedPreferences() function must be called with a specific name for the SharedPreferences file and the mode that should be used for storing the data to utilize default Shared Preferences. The data can only be viewed by the program that produced it since the default mode is MODE_PRIVATE.

The SharedPreferences class's many put-and-get methods may be used to store and retrieve data after the SharedPreferences file has been created.

Custom Shared Preferences

On the other side, the developer creates Custom Shared Preferences. They let the developer provide a special file name and access it with a special code. When different application components need to hold various types of data or when data has to be separated based on user accounts, custom shared preferences might be helpful. When an application has numerous instances and each instance has its own set of preferences, Custom Shared Preferences may also be utilized. For saving user-specific information that must endure over numerous sessions, Custom Shared Preferences can be very helpful. To save the user's height, weight, and exercise choices without having to be input again every time the application is used, a fitness application can employ custom Shared choices. The SharedPreferences.Editor class is used to modify the SharedPreferences file to use customized Shared Preferences. The apply() or commit() function is used to save the changes after using the put methods to add or alter data.

Using the Context.getSharedPreferences() function, custom shared preferences may also be made. When attempting to access Shared Preferences from a class other than an Activity class, this method accepts a Context object as an argument.

Nested Classes

SharedPreferences and nested classes.SharedPreferences as well as Editor. In Android programming, OnSharedPreferenceChangeListener is associated with Shared Preferences. Classes defined within another class are called nested classes. The SharedPreferences in the event of shared preferences.SharedPreferences and the Editor. The SharedPreferences interface contains nested OnSharedPreferenceChangeListener classes. This makes it possible for a more structured and unified method of maintaining shared preferences.

SharedPreferences.Editor

SharedPreferences.The editor is a nested class that provides a way to edit and update Shared Preferences. It allows the developer to add, remove, and modify key-value pairs in the Shared Preferences object. The SharedPreferences.Editor class provides several methods, such as putBoolean(), putInt(), and putString(), that can be used to add or update values in the Shared Preferences object. Once the changes have been made, they can be committed using the commit() or apply() methods.

SharedPreferences.OnSharedPreferenceChangeListener

SharedPreferences.OnSharedPreferenceChangeListener is another nested class that allows the developer to monitor changes in Shared Preferences. This class provides a callback method, onSharedPreferenceChanged(), that is triggered when a change is made to a key-value pair in the Shared Preferences object. The developer can register an instance of this class with the SharedPreferences object using the registerOnSharedPreferenceChangeListener() method. This allows the developer to perform actions or updates in response to changes in the Shared Preferences object.aredPreferenceChangeListener

Nested classes, SharedPreferences.Editor, and SharedPreferences.OnSharedPreferenceChangeListener are all important concepts related to Shared Preferences in Android development. The nested classes provide a more organized structure for managing Shared Preferences, while the SharedPreferences.Editor class provides a way to edit and update Shared Preferences. The SharedPreferences.The onSharedPreferenceChangeListener class allows the developer to monitor changes in Shared Preferences and respond accordingly. Understanding these concepts is crucial for any Android developer who needs to work with Shared Preferences.

Public Methods

To access and manage the preference data, Shared Preferences in Android offers several public methods. To read, write, and delete preferences data, utilize these available methods from the SharedPreferences class.

The most often used public Shared Preferences mechanisms are:

  • getSharedPreferences() : This function provides a SharedPreferences class instance that may be used to read or write preferences data.
  • edit(): This function returns a SharedPreferences.Editor class object that may be used to edit the preferences data.
  • getAll() : The getAll() function provides a Map that contains every key-value pair found in the preferences data.
  • getString(key, defaultValue) : This method retrieves the String value from the preferences data that corresponds to the specified key. It returns the designated default value if the key cannot be located.
  • putString(key, value) : This function creates the String value in the preferences database that corresponds to the specified key.
  • getInt(key, defaultValue) : This method returns the integer value in the preferences data that corresponds to the specified key. It returns the designated defaultvalue if the key cannot be located.
  • putInt(key, value) : This method changes the integer value in the preferences data that corresponds to the specified key.
  • getBoolean(key, defaultValue) : This method retrieves the boolean value included in the preferences data that corresponds to the specified key. It returns the designated defaultValue if the key cannot be located.
  • putBoolean(key, value) : This method changes the boolean value in the preferences data that corresponds to the specified key.
  • remove(key) : This method deletes the key-value pair from the preferences data that corresponds to the specified key.
  • contains(key) : This method returns true if the supplied key is present in the preferences data; otherwise, it returns false.

Storing and Retrieving Data with Shared Preferences

To save and retrieve user preferences and other application information, Shared Preferences offers a quick and easy solution. A quick explanation of how to use Shared Preferences for storing and retrieving data is provided below.

How to Store Primitive Data Types Using Shared Preferences?

Shared Preferences may store primitive data types including boolean, int, float, long, and String. We first need to get a hold of a SharedPreferences class object before we can start storing data with it. Use the getSharedPreferences() function, which accepts the name of the preferences file and the mode as its two parameters, to do this. Once we have a SharedPreferences class instance, we can add data to it using the SharedPreferences.Editor class. Depending on the data type we wish to save, we may add a value to the SharedPreferences object using the putBoolean(), putInt(), putFloat(), putLong(), or putString() methods. Utilizing the apply() or commit() methods of the SharedPreferences.Editor class, we can finally commit to the modifications.

For example, to store an integer value in Shared Preferences, we can use the following code:

Retrieving data from Shared Preferences

To get data from Shared Preferences, we must first get a SharedPreferences class object. The values of the data that we have saved may then be retrieved using methods like getBoolean(), getInt(), getFloat(), getLong(), and getString(). For example, to retrieve a boolean value from Shared Preferences, we can use the following code:

This code retrieves a boolean value from the SharedPreferences object with the key "isFirstLaunch". If the value is not found, the default value of true is returned.

Using Custom Objects with Shared Preferences

Shared Preferences cannot store custom objects; it can only store primitive data types. However, by transforming them into a format that Shared Preferences can comprehend, we may still utilize it to store customized objects. Serializing the item into a JSON string and saving it as a String in Shared Preferences is one typical method for accomplishing this. The JSON string may be obtained and deserialized back into an object when we need to get the object.

For example, suppose we have a custom object called Person that has the following properties:

We can serialize this object into a JSON string using the Gson library, and store it as a String in Shared Preferences. Here's an example of how to do this:

To retrieve the Person object, we can retrieve the JSON string from Shared Preferences and deserialize it using the Gson library:

Deleting and Clearing Data with Shared Preferences

In addition to storing and retrieving data, Shared Preferences also allows us to delete and clear data from the preferences file. This can be useful in situations where we want to remove specific data or reset the entire preferences file.

Deleting a Single Key-Value Pair from Shared Preferences

To delete a single key-value pair from Shared Preferences, we can use the remove() method of the SharedPreferences.Editor class. This method takes the key of the data we want to remove as its argument.

For example, suppose we have a boolean value called "isFirstLaunch" that we want to remove from the preferences file. We can use the following code to do this:

This program obtains a SharedPreferences object instance and builds a SharedPreferences.Editor class instance. The boolean value associated with the entry "isFirstLaunch" is then deleted from the preferences file using the remove() function. The apply() function is then used to apply the modifications.

Clearing All Data from Shared Preferences

The clear() function of the SharedPreferences.Editor class may be used to clear all data from Shared Preferences. By using this technique, the preferences file's key-value pairs are all deleted.

Let's say we wish to restore the preferences file to its original settings. To erase all information from the preferences file, use the following code:

This code generates an instance of the SharedPreferences.Editor class and obtains a SharedPreferences object instance. The clear() function is then used to delete all key-value pairs from the preferences file. Finally, it uses the apply() function to apply the modifications.

Future Advancements in Shared Preferences in Android Development

Various possible developments in Shared Preferences might improve its features and the user experience as technology continues to grow. Some of them include:

  • Secure Storage : The capacity to store data securely is one potential development for Shared Preferences. Data is now kept in plain text via Shared Preferences, making it susceptible to malicious attacks. To secure sensitive data, Shared Preferences may eventually include encryption and other security measures.
  • Cloud Syncing : Another possible development is the option to use cloud storage to sync Shared Preferences data between many devices. Users will have easy access to their preferences and settings from any device thanks to this. Additionally, users wouldn't have to manually copy their settings while switching between devices.
  • Custom Data Types : At the moment, only basic data types like booleans, integers, and texts are supported by Shared Preferences. It could later support unique data types like lists, arrays, and objects. As a result, data storage and retrieval would be more flexible, and developers would be able to build more intricate applications.
  • Improved Performance : Shared Preferences may need to be improved to keep up with the complexity of programs and the growing demand for data storage. This might entail caching a system to speed up read and write operations or optimizing the way data is stored and accessed.
  • Integration with Other Storage Solutions : Shared Preferences may be able to integrate with other storage options like Room databases or SQLite. In addition to enabling more complicated data structures and interactions, this would provide developers with additional alternatives for storing and retrieving data.
  • Advanced Configuration Options : Shared Preferences currently only offers a few advanced configuration options, such as the mode (private or public) and file name. In the future, it could come with more complex setup options including data expiry settings, compression, and encryption.
  • User-Defined Preferences : Lastly, Shared Preferences may let users create custom settings and preferences. Users will be able to tailor their application to their requirements and interests, creating a more personalized experience.

Conclusion

  • Shared Preferences is a feature in Android development that enables programmers to effectively store and retrieve tiny pieces of data, such as user preferences.
  • On the device's file system, Shared Preferences stores information in an XML file for use. A key-value pair system is used to obtain and update the data.
  • Given that it offers a quick and easy mechanism to save and retrieve user preferences and settings, Shared Preferences are crucial to Android development.
  • Default and customized shared preferences are the two different forms of shared preferences. The Android framework offers default Shared Preferences, however, developers construct their Shared Preferences.
  • It is simple to save data in Shared Preferences using the putBoolean(), putInt(), putFloat(), and putString() functions. Using the appropriate get methods, data from Shared Preferences is retrieved.
  • Secure data storage, cloud synchronization, personalized data kinds, enhanced performance, interaction with other storage systems, sophisticated configuration options, and user-defined preferences are a few potential future developments for Shared Preferences.