Working With Shared Preferences
Now it’s time to work with shared preferences by adding the following code just above btnSave.setOnClickListener
.
val sharedPreferences: SharedPreferences =
getSharedPreferences("user_data", Context.MODE_PRIVATE)
Here, you declare a variable of a type SharedPreferences
and initialize it with getSharedPreferences
, which takes two parameters. The first parameter is the name of the preference file. The second is the operation mode and is set to Context.MODE_PRIVATE
so only this app can access this file.
Next, add the following code inside btnSave.setOnClickListener
:
//1
val editor = sharedPreferences.edit()
//2
editor.putString("Name", etName.text.toString())
editor.putString("Email", etEmail.text.toString())
editor.putString("Phone", etPhone.text.toString())
//3
editor.apply()
//4
etName.setText("")
etEmail.setText("")
etPhone.setText("")
Here’s what you added:
-
sharedPreferences.edit()
: You call this method when you want to begin to presist your data.
-
editor.putString
: You use this when you want to save a String data type inside shared peferences. This takes two parameters. The first parameter is the name of the value you want store while the second is the value you want to store under this name.
-
editor.apply()
: Finally, you call this when you want to save values inside SharedPreferences
.
- After you save your data, you clear it from the screen. Here, you clear the name, email and phone number.
Build and run the app to see the progress.
Isn’t it cool to see it working? :] But you might be asking why the data that you entered doesn’t appear after you relaunch the app. Good question.
To solve that problem, add the following code at the bottom of onCreate
:
etName.setText(sharedPreferences.getString("Name", ""))
etEmail.setText(sharedPreferences.getString("Email", ""))
etPhone.setText(sharedPreferences.getString("Phone", ""))
Earlier you uses editor.putString
to save the data. To retrieve it you use sharedPreferences.getString("", "")
. You use getString
because the data type you initially saved was of type String
.
This takes two parameters: first is the name of the value that you want to retrieve, while the second parameter is a default value that you provide in case the original value is empty.
Now build and run the app to see the result.
Where to Go From Here?
You can download the completed end project by clicking on the Download Materials button at the top or bottom of this tutorial.
Be sure to check out AndroidX Biometric Library documentation to find out about other uses for this API, such as customization and cryptography.
I hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!