Difficulty: Beginner
If you have small values that you need to save in your app such as name, email or even the user`s choice of enabling dark mode, this can by easily done using shared preferences, shared preferences stores data in a key value pair this data can be shared or private to your app and its fully managed by the Android framework.
in this article we are going to explore how to use shared preferences to save the user’s name and retrieve it later even if the app is killed or the phone is rebooted.
UI
Our UI will consist of one edit text for input and two buttons for saving and loading the data to and from shared preferences respectively.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/et_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:ems="10"
android:hint="Enter your name"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="@+id/btn_save"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
<Button
android:id="@+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/btn_read"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/et_name" />
<Button
android:id="@+id/btn_read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="read"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/btn_save"
app:layout_constraintTop_toTopOf="@+id/btn_save" />
</androidx.constraintlayout.widget.ConstraintLayout>
MySharedPref class
In this step we will create a class and call it MySharedPref this class will be responsible for initializing the sharedPreferences object and providing us with some helper functions that we will use in our code to easily access our data in SharedPreferences
class MySharedPref(context: Context) {
companion object {
private const val FILE_KEY = "user_info"
}
private val sharedPref = context.getSharedPreferences(FILE_KEY, Context.MODE_PRIVATE)
}
In the block above we use the context to call getSharedPreferences function which will return the reference to our shared preferences that we save in a new val called sharedPref this val will hold a reference to our shared preferences file name “user_info”, instead of hard coding the string we saved it in a static constant called FILE_KEY. we pass ‘Context.MODE_PRIVATE’ for the second parameter to specify that we want this shared preferences file to be private.
import android.content.Context
/**
* Created by Taha (https://github.com/tahaak67) on 04,Feb,2023
*/
class MySharedPref(context: Context) {
companion object {
private const val FILE_KEY = "user_info"
private const val USER_NAME = "user_name"
}
private val sharedPref = context.getSharedPreferences(FILE_KEY, Context.MODE_PRIVATE)
fun saveUsername(name: String){
sharedPref.edit()
.putString(USER_NAME, name)
.apply()
}
fun getUsername(): String? {
return sharedPref.getString(USER_NAME, null)
}
}
saveUsername uses putString to save the new name received by the function and passes the key to this value ‘USER_NAME’, notice that we used edit on our sharedPref object to edit the value and called apply() after we finished editing.
getUsername uses the key to the name value ‘USER_NAME’ to get the value from shared preferences and return it.
Using MySharedPref in MainActivity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.basicsharedprefsample.databinding.ActivityMainBinding
import com.example.basicsharedprefsample.model.MySharedPref
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val pref = MySharedPref(this)
binding.apply {
btnRead.setOnClickListener {
etName.setText(pref.getUsername())
}
btnSave.setOnClickListener {
pref.saveUsername(etName.text.toString())
}
}
}
}
and just like this we can save our name in shared preferences and read it again using our buttons, Notice that i am using View Binding to access the views but you can use findViewById instead.
The sample project is available on Github.