SharedPreferences is one of the Data Storage options in Android that can be used to save and retrieve small amounts of data. Primitive datatypes such as String, int, float, and Boolean saved preferences in XML files inside the app. Also, SharedPreferences data is handled in Dictionary or key/value pair values.
SharedPreferences is used at different usages to save an app login in details (User name and password) in Session, to check whether the app user is in the login or not, and to pass the same value to one activity from another activity inside an app.
SharedPreferences object can be accessed at the app level and outside the app based on the MODE given while creating an object.
- MODE_PUBLIC SharedPreferences file can be accessed at the public level by other applications on the device.
- MODE_PRIVATE SharedPreferences files, saving private and secure at the app level.
- MODE_APPEND To read the data from the SP file.
Code Example
// Get the SharedPreferences object
SharedPreferences sharedPreferences = getSharedPreferences("myAppSharedPreferences", Context.MODE_PRIVATE);
// Get a SharedPreferences.Editor
SharedPreferences.Editor editor = sharedPreferences.edit();
// Writing data
editor.putString("EmployeeName", "exampleUser");
editor.putInt("EmployeeAge", 25);
// Commit the changes
editor.commit();
// Reading data
String employeeName = sharedPreferences.getString("EmployeeName", "defaultValue");
int employeeAge = sharedPreferences.getInt("EmployeeAge", 0);
SharedPreferences can be used in both Java and Kotlin programming languages, and they have the same fundamental concepts and methods. Also, Kotlin has some additional features, like explicitly declaring a data type and assigning a default null value to protect from null pointer exceptions.
Code Example
val sharedPreferences = getSharedPreferences("myAppPreferences", Context.MODE_PRIVATE)
val employeeName = sharedPreferences.getString("EmployeeName", "defaultValue")
val employeeAge = sharedPreferences.getInt("EmployeeAge", 0)
I will take the example of the Notes app and save the data using SharedPreferences, which is one good example of understanding SharedPreferences. Here, the title and description will be added in two text Views, then show all added notes in One container View.
activity_notes.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".NotesActivity">
<LinearLayout
android:layout_width="match_parent"
android:id="@+id/toolbar"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:background="#3CA74A"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="38dp"
android:text="Note App:"
android:layout_marginTop="16dp"
android:textStyle="bold"
android:id="@+id/TextView1" />
<Button
android:id="@+id/saveButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="save"
android:layout_marginTop="16dp" />
<EditText
android:id="@+id/titleEditText"
android:layout_width="match_parent"
android:background="@drawable/edittext_bg"
android:layout_height="46dp"
android:paddingLeft="10dp"
android:textColor="@color/black"
android:hint="Title" />
<EditText
android:layout_width="match_parent"
android:background="@drawable/edittext_bg"
android:layout_height="wrap_content"
android:hint="Description"
android:layout_marginTop="16dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="@color/black"
android:inputType="textMultiLine"
android:minLines="5"
android:id="@+id/contentEditText" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="18dp"
android:text="Notes"
android:layout_marginTop="16dp"
android:textStyle="bold"
android:id="@+id/notesTextView" />
<ScrollView
android:id="@+id/notesScrollView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/notesContainer"
android:orientation="vertical" />
</ScrollView>
</LinearLayout>
Java Code
private void loadNotesFromPreferences() {
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
int noteCount = sharedPreferences.getInt(KEY_NOTE_COUNT, 0);
for (int i = 0; i < noteCount; i++) {
String title = sharedPreferences.getString("note_title_" + i, "");
String content = sharedPreferences.getString("note_content_" + i, "");
Note note = new Note();
note.setTitle(title);
note.setContent(content);
noteList.add(note);
}
}
private void saveNotesToPreferences() {
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_NOTE_COUNT, noteList.size());
for (int i = 0; i < noteList.size(); i++) {
Note note = noteList.get(i);
editor.putString("note_title_" + i, note.getTitle());
editor.putString("note_content_" + i, note.getContent());
}
editor.apply();
}
Output