What are SharePreferences?
SharedPreferences is an android API that stores app data using key-value pairs and provides simple methods to read and write them.
Android system provides several options for you to save your data. These options are App-specific storage, Shared storage, Preferences, Databases. SharePreferences comes in Preference. It offers a framework to save private, primitive data in key-value pairs.
Why SharePreferences?
They’re mostly used to store user states when it comes to user settings or keeps a piece of small information(User details etc.) without needing storage permission. As per my opinion, you should store small primitive value in Preferences such as booleans, ints, longs, floats, and strings.
Modes in SharePreferences
SharedPreferences have different MODE these are below
1. Create a android application
Let take an example, open android studio, and create a new project. Now create a interface named is IPreferenceHelper. In this Interface we are defining some getter setter for storing or retrieving preference value. such as ApiKey and UserId etc.
2. Create a singleton class for managing Preferences
Ideally SharedPreferences store the app level value, So the SharedPreferences instance should be single threw out the app. It should be a singleton. Let create a Singletone class named is PreferenceManager and implement IPreferenceHelper. Just like below
3. Write into your SharedPreferences
Normally, writing into SharedPreferences is simple. But I’m going to write a Kotlin extension, This extension is make writing very simple and reduce boilerplate code.
4. Read from SharedPreferences
Reading a value from SharedPreferences is also straightforward. I’m going to write another useful extension that provides more control over retrieving a value from SharedPreferences. Let check below code
5. Finally your PreferenceManager class look like below
6. Access PreferenceManager into your presentation layers
Yes, Now your PreferenceManager class is ready for use. You can initialize PreferenceManager class into your ViewModel and Activity/Fragment, Make sure the context should be applicationContext.
7. Now open the activity_main.xml and paste below code.
For making interesting example I have added two edit text and one button in this layout
8. Let access PreferenceManager class in your source file
Let’s check the below code This way you can easily read and write the value in SharePreferences
7. Build & Test
Let run the app, in a movement your app will up and run, Now enter few value these EditText and click button. The value will display on TextView. android sharedpreferences tutorial,sharedpreferences,android studio,android sharedpreferences example,shared preference in android,android tutorial for beginners.This way you can read and write small amount of data in key-value pairs!