SharedPreferences in Android

Store Android application data more efficiently

Android provides many ways of storing an application’s data. One of these ways is called SharedPreferences. SharedPreferences allow you to save and retrieve data in the form of a key-value pair. It’s beneficial to use SharedPreferences APIs only when you have a relatively small collection of key-values that you’d like to save. Each SharedPreferences file is managed by the framework and can be private or shared.

Implementation in Android

1. Creation of a SharedPreference file

You can create a new SharedPreference file or access an existing one by calling one of these methods that returns a SharedPreference instance pointing to the file that contains the values of preferences. The two methods are mentioned below:

  • getSharedPreferences() — You can use this method if you need multiple SharedPreference files identified by name, which you specify with the first parameter. You can call this from any Context in your app. Therefore, it takes in two parameters: the first parameter is the key, and the second parameter is the MODE.
  • getPreferences() — You can use this method from an Activity if you need to use only one SharedPreference file for the activity. Because this retrieves a default SharedPreference file that belongs to the activity, you don’t need to supply a name. As such, this method takes only one parameter, the operation MODE. This function works by internally calling the underlying getSharedPreferences(String, Int) method by passing in the activity’s class name (from where it’s called and used) as the preference name.

Note: Different MODES that can be used are:

  1. MODE_PRIVATEIt is the default mode. Setting this mode means that only the application creating the shared preference can read-write the preference (or it can be accessed using all applications sharing the same user ID).
  2. MODE_APPEND This will append the new preferences with the already-existing preferences.
  3. MODE_ENABLE_WRITE_AHEAD_LOGGING Database open flag—when set, the database is opened with write-ahead logging enabled by default.
  4. MODE_MULTI_PROCESS This mode will check for the modification of preferences, even if the SharedPreference instance has already been loaded.
  5. MODE_WORLD_READABLEThis mode allows other applications to read the preferences.
  6. MODE_WORLD_WRITEABLEThis mode allows other applications to write the preferences.

2. Editing and Saving data in the SharedPreference file

You can edit and save something in the SharedPreferences file by using the SharedPreferences.Editor class. You’ll call the edit method of the SharedPreference instance and receive it in an editor object, to which you can pass the value that has to be saved.

For example:

You can also commit() the SharedPreference value to store it. But it’s recommended to use apply() to save it, given the following reasons:

  • commit() writes the data synchronously (blocking the thread its called from). It then informs you about the success of the operation, i.e. returns true if the save works, false otherwise.
  • apply() schedules the data to be written asynchronously. It doesn’t inform you about the success of the operation. It was added as the Android dev team noticed that almost no one took notice of the return value, so apply() is faster as it’s asynchronous.

Note 1: Apart from the putString method, there are many other methods available in the editor class that allow data manipulation inside SharedPreferences. They are listed as follows:

  • clear() will remove all values from the editor.
  • remove(String key) will remove the value whose key has been passed as a parameter.
  • putLong(String key, long value) will save a long value in a preference editor.
  • putInt(String key, int value) will save an integer value in a preference editor.
  • putFloat(String key, float value) will save a float value in a preference editor.

Note 2: If you want to store complex data like class objects in your preferences, you can use the GSON dependency.

  • Add the following dependency in your Gradle file:
  • To save data:-
val myObject = MyObject()
//set variables of 'myObject', etc..
// val editor = prefs.edit() -> gives the SharedPreferences.Editor
val gson = Gson();
val json = gson.toJson(myObject);
editor.putString("MyObject", json);
editor.apply();
  • To retrieve:
val json = prefs.getString("MyObject", "")

//returns the object of MyObject class that was saved earlier
val obj = gson.fromJson(json, MyObject::class.java)

The sample app has an edit text that saves in the text corresponding to a serial number provided by the user in the SharedPreference file by clicking on the save button. The latest text is restored from the SharedPreference file when asked by the user by clicking on the restore button.

Here’s the full code of the MainActivity:

import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    val KEY_DATA = "data"
    val KEY_APP_OPEN = "app_open"
    var appOpenCount = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

//      val prefs= getSharedPreferences("MyPreferences", Context.MODE_PRIVATE)
        val prefs = getPreferences(Context.MODE_PRIVATE)

        appOpenCount = prefs.getInt(KEY_APP_OPEN, 0)
        appOpenCount++

        prefs.edit {
            putInt(KEY_APP_OPEN, appOpenCount)
        }

        tvOpenCount.text = appOpenCount.toString()

        btnSave.setOnClickListener {
            prefs.edit().putString(KEY_DATA, etData.text.toString()).apply()

//            prefs.edit {
//                putString(KEY_DATA, etData.text.toString())
//            }
        }

        btnRestore.setOnClickListener {
            val data = prefs.getString(KEY_DATA, "")
            etData.setText(data)
        }
    }
}

And here’s the code of the layout.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:context=".MainActivity">

    <TextView
        android:textSize="20sp"
        android:id="@+id/tvOpenCount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/etData"
        android:layout_width="200dp"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnSave"
        android:text="SAVE"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/btnRestore"
        android:text="RESTORE"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Conclusion

To conclude, we can see that SharedPreferences works on a Key-Value basis and you simply provide the key and get back the value you stored. It’s useful when the data to be stored is small or simple like String or boolean values, etc. Also, one of the convenient features of SharedPreferences is that you can share data between two applications using it; so if you have two applications that have to share user preferences with each other, using SharedPreferences might be a convenient choice.

But do remember one thing that you should not store large amounts of data in SharedPreferences because if you try to store a large amount of data in it, it is going to cause some more usage of critical memory of your app, thereby reducing the speed and efficiency.

Hence, they allow quicker and simpler access to data only when data is small. If data is in huge amounts go for SQLite/Room.

Link to the GitHub repository:

Thanks for reading! If you enjoyed this story, please click the 👏 button and share it to help others find it!

Have feedback? Let’s connect on Twitter.

Fritz

Our team has been at the forefront of Artificial Intelligence and Machine Learning research for more than 15 years and we're using our collective intelligence to help others learn, understand and grow using these new technologies in ethical and sustainable ways.

Comments 0 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

wix banner square