Looking For Anything Specific?

Android SharedPreference In Kotlin With Sample Code

 Hi There,

Its good to see you again here, In the previous articles we have shared some useful information about how to work with the ActivityResult API in android which is to get results from activities, that was a very useful approach when the data is passed between single activity, But in some cases, you may want to share data between multiple activities, or to be precise you want to store a piece of information that the user has provided, for example, some basic information about the user like name age and sex. 

Android Activity Result API Tutorial In Kotlin 

These are simple information about the user and these data doesn't change frequently and the amount of data is very small, so in these case, if we want to store a piece of information about the user in your application you can use shared preference in android which is used to store information in Key-value format to an XML file in your apps data directory. So for data that does not have a complex structure or requires a do some operation in order to show we can store those kinds of data in android shared preference

android shared preference sample code kotlin tutorial

Access Shared Preference To Store Or Retrieve Data:

Android shared preference API is provided by the system for us to use to store or retrieve the data, so first, we access the shared preference by calling getSharedPreference() function, which requires two parameters the first one is the preference file's name where the data are going to be stored and the second one is the mode which is that the android context use this flag to create and edit the preference file, for this we provide Context.MODE_PRIVATE, which tells the android system that only our application can add or edit the contents of the file.

private val sharedPreference: SharedPreferences by lazy {
        getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE)
    }

In the above code, we use kotlin lazy delegate properties to initialize the get shared preference, with a PREF_NAME constant string name of our preference and as mentioned earlier Context.MODE_PRIVATE, there are other context modes available some of them were deprecated and some don't really match/fulfill our use case so we are going with MODE_PRIVATE.

ViewPager2 Example Code In Kotlin

How To Add RecyclerView In Android With Kotlin

How To Store Data In Android Shared Preference:

Now that we have our shared preference, we can able to store data in a key-value format, which is like structured data where each key have its own value, because of that we need to have a String Key in order to store a value in the shared preference, so we defined our string key for shared preference in constants as these should not change const val SAMPLE_STRING = "SAMPLE_STRING" this is our string key for this key alone we are going to store the data, it is a good practice to mention the data type of the value being store because shared preferences are not type-safe, about this we discussed in the next section of the article, let's have a look at the code to store the data 

button.setOnClickListener {
            sharedPreference.edit {
                putString(SAMPLE_STRING,editText.text.toString())
            }

            setPreferenceTextIfAvailable()
        }

Above is click listener to a button in android inside which we store the data to shared preference, what we are doing here is that we use the edit{} lambda function provided from the shared preference API which will have the SharedPreference.Editor which will be used to add or modify the values in the shared preference object, the editor is responsible for handling the data you are providing and you are responsible to provide the data properly, the editor will give you a put function with the prefix of the data type you want to store, for example, if you want to store a string as in our example you have to use the putString function which will accept two parameters which are the key and the value of type string, and in case if you want to store data of type integer you have to use putInt function with key as a string and value as type integer, in this example we use the key from constants and get the value from the editText.

You can also add multiple values at the same time, by chaining the put method, if you want to also store some integer value along with the above string use the same editor with putInt() function with key and the integer value to store more than one values at a time.

edit{} lambda will internally call commit() or apply() based on our choice to store the data to shared preference until you commit or apply those values will not be reflected in your shared preference, Additionally, you can define what you want to use commit or apply to make the data changes by providing a named parameter called commit = Boolean value to decide. 

Learn How to Add Click Listener To A Button In Android With Kotlin

The major difference between apply() and commit() is that commit stores data synchronously and will return a result upon successful storage of data whereas apply() make the changes to the data asynchronously. So don't mix commit and apply call with the same preference.

how to use android shared preference to save data with kotlin

How To Get Stored Data From Android Shared Preference:

Once the data are stored successfully, you can able to access them whenever you want, until either you deleter those data or the user clears data of your application from settings, Earlier we mentioned that it is good practice to mention the type of data store in the prefix of the key, because same as storing data in order to get the data from the preference we have to use some of the functions provided, and they are type-specific, so if you want to get the string from you shared preference you have to use getString() function with key and a default value to access the data back from persistent storage. Refer to the code below to get a clear picture:

private fun setPreferenceTextIfAvailable() {
        if (sharedPreference.contains(SAMPLE_STRING)) {
            textView.text =
                getString(R.string.stored_text, sharedPreference.getString(SAMPLE_STRING, ""))
        }
    }

Like explained above, in this little function we use the shared preference object to get the value and show it in a textView, for additional safety we use the contains function to check where the preference has any values associated with the given string, this ensures us to not to access values that are not available in the storage, after that we use the getString on a sharedPreference to get the string for the provided key, don't get confused with the first getString that is to get the string from my XML.

Like putting the string to the preferences, for retrieving the data also have to use type-specific function so to get int we use getInt(), but the general idea is the same, to get data we provide key and default value, to store we provide key with actual value. 

How To Create Custom CheckBox In Android

Editing Values Already Stored In Shared Preference: 

Editing a value in the preference is actually not a separate operation because of the SharedPreference.Editor will take care of it for us, if we use putString() on any previously available value the preference will simply replace the value for us.

How To Remove Values Store In Shared Preference: 

So, now we can able to add or edit and retrieve the values in our shared preference, what if we want to remove the value already stored in the preference, that is also a simple operation like adding the values, we simply access the editor inside the edit{} lambda function and call remove with the string key of the value we want to remove from the preference.
deleteButton.setOnClickListener {
            sharedPreference.edit {
                remove(SAMPLE_STRING)
            }
            textView.text = getString(R.string.data_removed)
        }

 So we added a little button to our existing UI to demonstrate the delete functionality and we will display a "Data removed" text once the data is deleted from the storage. Also, there is another way to remove data is, you can use the putString method itself to remove the data by passing null as value to the key for which you want to remove the value to avoid passing null to putString.

tutorial on how to remove data store in shared preference in android with kotlin

How To Remove All Data From Shared preference: 

Alternatively, if you have more than one data stored in your preferences and want to remove it all at once you can use the clear() function in the SharedPreference.Editior which will remove all the data in the preference. 

Conclusion:

These are the example code you use to do simple operation on simple data in android share preference with kotlin, always keep the data simple and use it to store only less information, not for large lists for which cases use Databases, Keep an eye on the data type when storing and retrieving. Hope this article helps, Don't forget to like my Facebook page. You can get the complete project code from the GitHub link below: https://github.com/blackzshaik/AndroidSaveSimpleData


!!! Thank You !!!

!!! Sharing is Caring !!!

keywords:

Shared preference login example in android

How to store multiple values in SharedPreferences in Android

How to get data from SharedPreferences in Android

How to use SharedPreferences in Android

Post a Comment

0 Comments