Shared Preferences in Android

Nishanth Mekala
5 min readOct 29, 2021

In this post, let's learn an interesting topic called SharedPreferences.

Before diving deep, we will have a look at some of the important points regarding SharedPreferences

  • SharedPreferences are used to store small amounts of data in the form of key-value pairs in a file.
  • In general, the data we store using SharedPreferences consists of user preferences or the data that is accessed across multiple activities in the same app.
  • The data we store in a file using SharedPreferences would actually be in XML format.
  • These files are stored locally in the application directory and thus deleted when the app is uninstalled.
  • If we close our app and open it again, we can still access the data that we stored, before closing the app, in SharedPreferences.
  • As you know, onPause() will always be called before your activity is placed in the background or destroyed, So the data to be saved persistently, it’s preferred to save it onPause(), which could be restored in onCreate() of the activity.

APIs for accessing Preferences in Android

There are three types of preferences and we can access them using three APIs as below

sharedPreference object that we get from the APIs actually points to the file in which data is stored.

*getPreference(): Use this from an activity if you need to use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don’t need to supply a name.

*getSharedPreference(): Use this if you need multiple shared preferences files identified by name, which you specify with the first parameter. You can call this from any context in your app.

*getDefaultSharedPreference(): Use this to get the default shared preference file for your entire app. It is used to save your app settings.

The name we give to the file should be uniquely identified by the app. For example, we can prefix the file name with the application package name.

Writing the shared preference file

sharedPreference.edit() method gives us an editor object that is used to write/clear the data in the preference file.

// Storing data into SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences(“MySharedPref”,MODE_PRIVATE);
// Creating an Editor object to edit(write to the file)
SharedPreferences.Editor editor = sharedPreferences.edit();
// Storing the key and its value as the data fetched from edittext
editor.putString(“name”, name.getText().toString());
editor.putInt(“age”, Integer.parseInt(age.getText().toString()));
// Once the changes have been made,
// we need to commit to apply those changes made,
// otherwise, it will throw an error
editor.commit();
/*
editor.clear() clears the entire data in the file
*/

Actually we can use editor.commit() or editor.apply() to save the changes.

editor.commit() save the changes immediately in the Main thread itself and thus might block UI.

editor.apply() does not run in the main thread and thus not save changes immadiately.

Reading the shared preference file

// Retrieving the value using its keys the file name// must be same in both saving and retrieving the dataSharedPreferences sh = getSharedPreferences("MySharedPref", MODE_APPEND);// The value will be default as empty string because for// the very first time when the app is opened, there is nothing to showString s1 = sh.getString("name", "");

Modes of SharedPreference File

Actually, we can get shared preference files from the APIs in certain modes as below

  • MODE_PRIVATE : Keeps files private and secures data.
  • MODE_APPEND : Used to read data.
  • MODE_PUBLIC : Files we get this way can be accessed from any other apps.

Example :

SharedPreferences sh = getSharedPreferences("MySharedPref", MODE_APPEND);

Some methods of Shared Preferences

  1. contains(String key): This method is used to check if the data with the passed key is present or not. This returns a boolean value
  2. edit(): As already said, this method is used to create SharedPreferences.Editor object which helps us to write/clear data in the file.
  3. getPrimitiveDataType(String key, PrimitiveDataType defValue): This method is used to retrieve a value of type PrimitiveDataType from the file with the default returned value (in case of failure) being defValue.
  4. registerOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to register a callback to be invoked when a change happens to a preference.
  5. unregisterOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to unregisters a previous callback.

Let's look at a final touch example as below

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="HardcodedText">
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="Shared Preferences Demo"
android:textColor="@android:color/black"
android:textSize="24sp" />
<!--EditText to take the data from the user
and save the data in SharedPreferences-->
<EditText
android:id="@+id/edit1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textview"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:hint="Enter your Name"
android:padding="10dp" />
<!--EditText to take the data from the user and
save the data in SharedPreferences-->
<EditText
android:id="@+id/edit2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/edit1"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:hint="Enter your Age"
android:padding="10dp" />
</RelativeLayout>

Output UI

Java

import androidx.appcompat.app.AppCompatActivity;import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {private EditText name, age;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.edit1);
age = findViewById(R.id.edit2);
}
// Fetch the stored data in onResume()
// Because this is what will be called
// when the app opens again
@Override
protected void onResume() {
super.onResume();
// Fetching the stored data
// from the SharedPreference
SharedPreferences sh = getSharedPreferences("MySharedPref", MODE_PRIVATE);
String s1 = sh.getString("name", "");
int a = sh.getInt("age", 0);
// Setting the fetched data
// in the EditTexts
name.setText(s1);
age.setText(String.valueOf(a));
}
// Store the data in the SharedPreference
// in the onPause() method
// When the user closes the application
// onPause() will be called
// and data will be stored
@Override
protected void onPause() {
super.onPause();
// Creating a shared pref object
// with a file name "MySharedPref"
// in private mode
SharedPreferences sharedPreferences = getSharedPreferences("MySharedPref", MODE_PRIVATE);
SharedPreferences.Editor myEdit = sharedPreferences.edit();
// write all the data entered by the user in SharedPreference and apply
myEdit.putString("name", name.getText().toString());
myEdit.putInt("age", Integer.parseInt(age.getText().toString()));
myEdit.apply();
}
}

Why can’t we use savedInstanceState bundle instead of SharedPreference?

  • SharedPreference is used when we want to persist the data even after closing the app so that we can access the data after re-opening the app. We can’t do that using savedInstanceState bundle as the data in that bundle becomes volatile once we close the app.
  • SharePreference is used to access the same data across many activities but it's not possible with that bundle.
  • SharedPreference is generally used to store users' preferences whereas that bundle is used to store an activity’s UI state.

That’s it, guys. Hope you have understood it well.

Clapp, to encourage me to bring many more android posts.

--

--