Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

sharedpreference
android storage
communitycreator

What is shared preference in Android-Kotlin?

Ilori AbdulRasheed

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Introduction

Shared-Preference is an interface to store and preserve data in android.

An interface is a class in the Object-Oriented-Programming concept, (OOP), which consists of methods or behavior of object belonging to that class. It accesses and modifies preference data returned by:  Context.getSharedPreferences(String, int).

A single instance of this class is called that all clients share.

An object of this class points to a file containing key-value pairs and provides simple methods to read and write them.

Figure 1.1: Shared Preference key- value pair storage outside android lifecycle

Handling shared preferences

The following methods can be called if you want to create a new shared preference file or share an existing file:

getSharedPreference()

You can use this when you require more than one shared preference file, identified by name and specified with the first parameter. This can be called from any Context in your app.

val sharedPref = activity?.getSharedPreferences( getString(
R.string.preference_file_key), Context.MODE_PRIVATE)
Instantiating object of getting shared preferences
getPreferences()

This is used from an Activity if you need to use only one shared preference file for the activity. You don’t need to supply a name because this method retrieves a default shared preference file that belongs to the activity.

val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
Instantiating object of getting preferences

Note: Use a name that is uniquely identifiable to your app. Prefixing it with your app’s name is a good way to start.

Writing to shared preference

Call the edit() method on the instance of your SharedPreference you created. You can pass the keys and values that you want to write by using methods like putInt() and putString(). Then, to save changes, call apply() or commit().

For example:

val sharedPref = activity?
.getPreferences(Context.MODE_PRIVATE) ?: return
with (sharedPref.edit()) {
putInt(getString(R.string.saved_high_score_key), newHighScore)
    apply()
}
Code demonstrating how to set the sharedPreference to use

Reading from shared preference

You can read the data stored by calling methods like getInt() and getString(). You must provide the key for the desired value, and optionally include a default value to be returned in case the key is not present. For instance:

val sharedPref = activity?
.getPreferences(Context.MODE_PRIVATE) ?: return
val defaultValue = resources.getInteger(R.integer.saved_high_score_default_key)
val highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue)
Getting data from Preference

commit() and apply()

With commit(), your preferences change back from this Editor to the SharedPreferences object it is editing. This automically performs the requested modifications, replacing whatever is currently in the SharedPreferences. If two editors modify at the same time, the last one to call apply() wins.

Unlike commit(), which performs persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately in an asynchronous commit to disk and you won’t be notified of any failures.

If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

With apply(), you don’t need to worry about Android component lifecycles and their interaction. The framework ensures in-flight disk writes from apply() are completed before switching states.

Conclusion

Android has different life-cycle operations which range from onStart(), onCreate(), onPause(), onResume(), onStop(), onRestart(), onOrientationChange(), onStop(), onDestroyed(), etc. This means that when you use your android phone, these stages of lifecycle operation follow sequentially, get destroyed, and then are restarted again.

Data stored during the previous state get destroyed when another life-cycle started again.

Shared Preference is one of those four specific storage options to keep this data so that if a lifecycle gets destroyed, the app can access the previous data from the last operation, then rebuild. That is the reason for switching one app to the background (in simple terms) and retrieving it after a long time, upon which your app resumes from where it was pushed to the background.

Although Shared Preference stores primitive data in keys and values, its consistency is guaranteed.

Other options still exist such as shared storage (files, media, etc.), Database, and App-specific storage like the room database.

RELATED TAGS

sharedpreference
android storage
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring