Did you ever marvel easy methods to retailer some values in your software with out dropping them after closing the app? Android gives a means to do this you probably have a small assortment of key values you’d like to avoid wasting!
On this article, we’ll check out Android’s SharedPreferences
APIs after which reveal easy methods to use SharedPreferences
in a use case.
Jetpack DataStore is a contemporary resolution that makes use of Kotlin coroutines and Move to retailer information asynchronously. Sooner or later, you would possibly think about migrating to Jetpack DataStore from SharedPreferences
. Nevertheless, on this article we’ll deal with SharedPreferences
because it stays helpful and remains to be highly regarded as of this writing.
Soar forward:
What’s SharedPreferences
?
SharedPreferences
is an Android API that lets you create and entry a file containing a key-values assortment. A SharedPreferences
object gives some strategies for studying and writing these values on the file. Every SharedPreferences
file is managed by the framework and may be personal to the applying or shared.
Accessing
To create or entry a SharedPreferences
file, you possibly can name both of the next strategies: getSharedPreferences()
or getDefaultSharedPreferences()
.
Let’s have a look.
getSharedPreferences(title, mode)
Use the getSharedPreferences() methodology if it’s essential create or entry a SharedPreferences
file recognized by title.
Right here’s an instance of this methodology:
val sharedPreferences = exercise?.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE)
getDefaultSharedPreferences()
Use the getDefaultSharedPreferences() methodology to get the default SharedPreferences file for a complete app. You need to be conscious that this methodology requires further dependency.
The beneath instance of this methodology requires an additional dependency to be added to the construct.gradle
file on the app module stage:
Right here’s the dependency:
implementation "androidx.desire:preference-ktx:1.2.0"
Right here’s an instance of the tactic:
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
Sharing recordsdata
The second parameter of the getSharedPreferences
methodology is the mode. This parameter pertains to permissions for file sharing.
Sharing recordsdata with different purposes
To share personal recordsdata with purposes that don’t share your person ID, you need to use MODE_WORLD_READABLE
with Android variations older than 7.0. Android 7.0+ will throw a safety exception if you happen to try to make use of this mode; it has been deprecated since API stage 17.
When you run into this concern, a workaround is to make use of a FileProvider with the intent set to FLAG_GRANT_READ_URI_PERMISSION
. For extra info, additionally see the official documentation on sharing recordsdata.
Sharing recordsdata together with your software
To share personal recordsdata with any software that shares your person ID, you need to use MODE_PRIVATE
.
Studying
To retrieve values from a SharedPreferences
file, you possibly can name any of the beneath strategies, offering the important thing for the worth you need and an non-compulsory default worth to return if the important thing doesn’t exist:
accommodates(key: String)
Use this methodology to examine if the preferences file accommodates a particular desireedit()
Use this methodology to create a brand new Editor, by which you can also make atomic adjustments to the information within theSharedPreferences
filegetAll()
Use this methodology to retrieve all values within theSharedPreferences
filegetInt(key: String, defValue: Integer)
Use this methodology to retrieve anInteger
worth from theSharedPreferences
filegetBoolean(key: String, defValue: Boolean)
Use this methodology to retrieve aBoolean
worth from theSharedPreferences
filegetFloat(key: String, defValue: Float)
Use this methodology to retrieve aFloat
worth from theSharedPreferences
filegetLong(key: String, defValue: Lengthy)
Use this methodology to retrieve aLengthy
worth from theSharedPreferences
filegetString(key: String, defValue: String)
Use this methodology to retrieve aString
worth from theSharedPreferences
filegetStringSet(key: String, defValues: Set)
Use this methodology to retrieve a set ofString
values from theSharedPreferences
file
Writing
To write down values in a SharedPreferences
file, create a SharedPreferences.Editor
by calling edit()
in your SharedPreferences
object. With edit()
, you’ll be capable to name the next strategies:
putInt(key: String, worth: Integer)
Use this methodology to insert anInteger
worth on theSharedPreferences
fileputBoolean(key: String, worth: Boolean)
Use this methodology to insert aBoolean
worth on theSharedPreferences
fileputFloat(key: String, worth: Float)
Use this methodology to insert aFloat
worth on theSharedPreferences
fileputLong(key: String, worth: Lengthy)
Use this methodology to insert aLengthy
worth on theSharedPreferences
fileputString(key: String, worth: String)
Use this methodology to insert aString
worth on theSharedPreferences
fileputStringSet(key: String, values: Set)
Use this methodology to insert a set ofString
values on theSharedPreferences
file
Extra nice articles from LogRocket:
After writing adjustments, you’ll want to name apply()
or commit()
to avoid wasting your adjustments. In line with the official Android documentation, each apply()
and commit()
change the in-memory SharedPreferences
object instantly however write updates to the disk in another way. apply()
writes updates asynchronously, whereas commit()
writes updates synchronously and will lead to paused UI rendering if known as from the principle thread.
Right here’s an instance illustrating a number of the above capabilities to retrieve and write values in a SharedPreferences
file:
val sharedPref = exercise?.getPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE) ?: return with (sharedPref.edit()) { putInt(getString(R.string.saved_high_score_key), newHighScore) apply() }
Detecting adjustments
To detect adjustments in a SharedPreferences
file, you possibly can name the next strategies:
registerOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferencechangeListener)
Use this methodology to register a callback that will get invoked when a change occurs within theSharedPreferences
fileunregisterOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferencechangeListener)
Use this methodology to unregister a callback that will get invoked when a change occurs within theSharedPreferences
file
SharedPreferences
use case
Now, we’ll check out a standard situation during which SharedPreferences
could also be helpful. Let’s say you wish to show an onboarding web page the primary time a person opens an app.
To make this work, you’ll have to have a Boolean worth saved in a SharedPreferences
file indicating whether or not or not it’s the first time a selected person has opened the app.
Implementation
To start out, open res/values/strings.xml
and add the title of our SharedPreferences
file.
Subsequent, add the next code to the strings.xml
file:
<string title="app_shared_prefs">com.pp.sharedprefs.PREFERENCES_FILE_KEY</string>
You’ll additionally want so as to add a key that identifies our saved worth. Let’s name it FIRST_TIME_OPENING_KEY
.
Add the next code to the strings.xml
file:
<string title="first_time_opening">FIRST_TIME_OPENING_KEY</string>
Now, go to your exercise and add the next code inside onCreate(savedInstanceState: Bundle?)
after setContentView()
is known as:
getSharedPreferences(getString(R.string.app_shared_prefs), Context.MODE_PRIVATE)?.let { sharedPreferences -> val isFirstTimeOpening = sharedPreferences.getBoolean(getString(R.string.first_time_opening), true) if (isFirstTimeOpening) { showOnboarding() with (sharedPreferences.edit()) { putBoolean(getString(R.string.first_time_opening), false) apply() } } }
Within the above code, we get entry to the file by calling getSharedPreferences(title, mode)
.
Subsequent, we attempt to get the worth of our FIRST_TIME_OPENING_KEY
from the SharedPreferences
file. If the worth is nonexistent, we return true
.
If we return true
, that is the primary time the person is opening the app. On this case, we present the onboarding display and alter the worth of FIRST_TIME_OPENING_KEY
to false
so the person won’t see the onboarding display once more. Then, we name apply()
to conclude the adjustments.
That ought to do it!
In our use case instance, we dealt with an onboarding display. Nevertheless, this resolution works for something that you simply wish to be run solely as soon as, when the person opens the app for the primary time.
A small further: Lowering the code size
Since we’re utilizing Kotlin, we will use its energy to scale back the code size a bit with Kotlin extensions.
To make use of Kotlin extensions, create a separate file known as SharedPreferencesHelper
after which add the next:
enjoyable SharedPreferences.edit(actions: SharedPreferences.Editor.() -> Unit) { with (edit()) { actions(this) apply() } }
The above code will add an extension operate known as edit
to the SharedPreferences interface
. The edit()
operate takes a Kotlin lambda operate, which is outlined by curly braces and is an extension of SharedPreferences.Editor
.
On this extension operate, we’re already calling apply()
on the finish, so there’s no have to repeat that when utilizing this extension so as to add values within the SharedPreferences
file.
Return to the Exercise, and change the next code:
with (sharedPreferences.edit()) { putBoolean(getString(R.string.first_time_opening), false) apply() }
With the next snippet:
sharedPreferences.edit { putBoolean(getString(R.string.first_time_opening), false) }
This shorter code ought to present the identical consequence!
Conclusion
On this article, we investigated and provided options to make use of SharedPreferences
API. We demonstrated easy methods to use SharedPreferences
in an instance involving an onboarding display.
For extra info on this matter, take a look at the official docs on: SharedPreferences, Jetpack DataStore, and Kotlin extensions.
Thanks for studying. I hope this text makes your life simpler whereas working with SharedPreferences
!
LogRocket: Immediately recreate points in your Android apps.
LogRocket is an Android monitoring resolution that helps you reproduce points immediately, prioritize bugs, and perceive efficiency in your Android apps.
LogRocket additionally helps you improve conversion charges and product utilization by exhibiting you precisely how customers are interacting together with your app. LogRocket’s product analytics options floor the the explanation why customers do not full a selected circulation or do not undertake a brand new function.
Begin proactively monitoring your Android apps — strive LogRocket free of charge.