Learn how to use shared preferences in Android

Learn how you can use shared preferences in you Android project. This article will guide you with step by step breakdown of how you can use the shared preferences available in Android to store simple key value pairs.

Quick Navigation

What is shared preferences in Android ?

To fully understand shared preferences we must first look at why was it required in the first place.

As we know that we cannot retain the values once the application has exited. We need some form of mechanism to persist the data in our application. That’s where shared preferences in Android comes in.

Shared preferences are just xml files in android that hold simple key value pairs of data.

Example: name -> techenum

That is it nothing more nothing less. However it does support other basic datatypes.

Also Read : Learn how to use fileprovider in Android with example


Shared preferences simple structure

Before continuing with out example we will look at how the shared preferences work. Do not copy the code below, it will not work. It’s just for an example on how to use shared preferences.

Let us look at the code below:

val application = Application() val pref = applicatino.getSharedPreferences("_name_of_preference", Context.MODE_PRIVATE)
Code language: Kotlin (kotlin)

Now that we have created a new instance of shared preferences let us save some value:

val isSuccess = pref.edit().putString("name", "Techenum").commit()
Code language: Kotlin (kotlin)

We have saved our value. Now let us see how can we retrieve the value.

val name = pref.getString("name", null) // here null is the default value which is returned if the key is not found
Code language: Kotlin (kotlin)

Now that we have learn the basics of shared preferences in Android. Let us slightly modify the things we have learned and complete our project.

Also Read: Learn How To Create Tabs With ViewPager2


Creating a shared preferences helper

Let us create a new Kotlin class named SpHelper where we will put the shared preferences code.

@SuppressLint("ApplySharedPref") class SpHelper private constructor(private val mSharedPreference: SharedPreferences) { fun save(key: String, value: String) { mSharedPreference.edit().putString(key, value).commit() } fun save(key: String, value: Boolean) { mSharedPreference.edit().putBoolean(key, value).commit() } fun save(key: String, value: Long) { mSharedPreference.edit().putLong(key, value).commit() } fun save(key: String, value: Int) { mSharedPreference.edit().putInt(key, value).commit() } fun get(key: String, default: String?): String? { return mSharedPreference.getString(key, default) } fun get(key: String, default: Boolean): Boolean { return mSharedPreference.getBoolean(key, default) } fun get(key: String, default: Long): Long { return mSharedPreference.getLong(key, default) } fun get(key: String, default: Int): Int { return mSharedPreference.getInt(key, default) } companion object { private lateinit var INSTANCE: SpHelper fun init(application: Application) { val sp = application.getSharedPreferences("_sp_test", Context.MODE_PRIVATE) INSTANCE = SpHelper(sp) } fun instance(): SpHelper { return INSTANCE } } }
Code language: Kotlin (kotlin)

What have I done with the code ? Let me explain

  • @SuppressLint("ApplySharedPref") supresses the lint warning on this class
  • We have each method to save all type of values save(key:String, value:String)
  • The method to retrieve the value has been added get(key: String, default: String): String

The companion object also holds a few method and member variables. What are they ?

We have SpHelper.init(application) to create a singleton instance of the helper class. And then we will use SpHelper.instance() to get instance whenever required.

Also Read : How to get current GPS location in Android


Creating UI and using our helper class

In our activity_main.xml we have the following code for a simple UI.

<?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"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="8dp" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.25" /> <EditText android:id="@+id/edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="32dp" android:layout_marginEnd="16dp" android:hint="Enter Some Value" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <Button android:id="@+id/button_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:text="Save" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="@+id/edit_text" app:layout_constraintTop_toBottomOf="@+id/edit_text" /> <Button android:id="@+id/button_load" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Load" app:layout_constraintBottom_toBottomOf="@+id/button_save" app:layout_constraintEnd_toEndOf="@+id/edit_text" app:layout_constraintHorizontal_bias="0.9" app:layout_constraintStart_toEndOf="@+id/button_save" /> </androidx.constraintlayout.widget.ConstraintLayout>
Code language: HTML, XML (xml)

Now to actually save the values from the activity. I have implemented the following portions in my code.

class MainActivity : AppCompatActivity(), View.OnClickListener { private lateinit var mEditText: EditText private lateinit var mSave: Button private lateinit var mLoad: Button private lateinit var mSpHelper: SpHelper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) SpHelper.init(application) mSpHelper = SpHelper.instance() mEditText = findViewById(R.id.edit_text) mSave = findViewById(R.id.button_save) mLoad = findViewById(R.id.button_load) mSave.setOnClickListener(this) mLoad.setOnClickListener(this) } override fun onClick(p0: View) { when (p0.id) { R.id.button_save -> { mSpHelper.save(PREF_KEY, mEditText.text.toString()) mEditText.setText("") Toast.makeText(this, "Value saved!", Toast.LENGTH_LONG).show() } R.id.button_load -> { mEditText.setText(mSpHelper.get(PREF_KEY, "-- value not found --")) } } } companion object { const val PREF_KEY = "key.pref.test" } }
Code language: Kotlin (kotlin)

In the onCreate() { } we have mapped the views to member instances.

Also we have implemented a click listener and assigned it to each button.

And in the companion object we have the key instance variable.

That is all we have learn how we can use shared preferences in Android.

You can check out the documentation for more here.

Also Read : Async Task in Android is Deprecated: There are Better Ways


Related Posts