Shared Preference
Shared Preference:
SharedPreferences is a kind of API used in Android operating system to store key-value pairs of basic data types permanently in the device.
It is most common to persist simple settings or some data that are needed to be preserved after a session or even after a device restart.
Example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".SharedPreferencesExample"
android:padding="16dp"
android:gravity="center"
android:orientation="vertical">
<EditText
android:id="@+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your message" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp"
android:gravity="center">
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Data"
android:textColor="@color/colorWhite"
android:textAllCaps="false"
android:background="@color/colorOrange"
android:padding="16dp"
android:layout_margin="16dp" />
<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display Data"
android:textColor="@color/colorWhite"
android:textAllCaps="false"
android:background="@color/colorOrange"
android:padding="16dp"
android:layout_margin="16dp" />
</LinearLayout>
<TextView
android:id="@+id/textDisplay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/colorAccent"
android:textSize="20dp"
android:padding="16dp"
android:gravity="center" />
</LinearLayout>
Output