

Android Shared Preferences Exampleįollowing is the example of storing and retrieving the primitive data type values from shared preferences file using SharedPreferences.Ĭreate a new android application using android studio and give names as SharedPreferencesExample.
#Shared preference manager how to#
Now we will see how to store and retrieve primitive data type key-value pairs in shared preferences file using SharedPreferences object in android application with examples. If you observe above code snippet, we are clearing all the values from shared preferences using a method called clear() and committing the changes to shared preferences file using commit() method. SharedPreferences.Editor editor = pref.edit()

SharedPreferences pref = getPreferences(Context. If we are using single shared preference file for our activity, then we need to initialize the SharedPreferences object by using getPreferences() method like as shown below. The following are the different ways to initialize the Shared Preferences in our application. We can call this from any Context in our app. This method is useful to get the values from multiple shared preference files by passing the name as a parameter to identify the file. This method is for activity level preferences and each activity will have its own preference file and by default, this method retrieves a default shared preference file that belongs to the activity. In case if we use a single file to save the preferences, then we need to use getPreferences() method to get the values from Shared Preferences file and for multiple files, we need to call a getSharedPreferences() method and pass a file name as a parameter. In android, we can save the preferences data either in single or multiple files based on our requirements. to maintain the state of the app, next time when they login again to the app.

The Shared Preferences are useful to store the small collection of key-values such as user’s login information, app preferences related to users, etc. The Shared Preferences file is managed by an android framework and it can be accessed anywhere within the app to read or write data into the file, but it’s not possible to access the file from any other app so it’s secured. Generally, the Shared Preferences object will point to a file that contains key-value pairs and provides a simple read and write methods to save and retrieve the key-value pairs from a file. In android, Shared Preferences are used to save and retrieve the primitive data types (integer, float, boolean, string, long) data in the form of key-value pairs from a file within an apps file structure.
