How to Use SharedPreferences in Android Studio (With Example)

How to Use SharedPreferences in Android Studio (With Example)

In Android development, SharedPreferences is used to store small amounts of data as key-value pairs, such as user preferences or simple settings. This data is stored persistently across app launches and remains until explicitly removed.

activity_shared_preference.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F0F4F8"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:background="#212121"
        android:gravity="center"
        android:text="Shared Preference Demo"
        android:textColor="#FEFEFE"
        android:textSize="30sp" />

    <EditText
        android:id="@+id/nameEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/rounded_edittext"
        android:hint="Enter your name"
        android:textSize="35sp" />

    <Button
        android:id="@+id/saveBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/rounded_button"
        android:text="Save Name"
        android:textSize="35sp" />

    <Button
        android:id="@+id/showBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/rounded_button"
        android:text="Show Saved Name"
        android:textSize="35sp" />

    <TextView
        android:id="@+id/savedName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:background="@drawable/rounded_result"
        android:text="Show Saved Name"
        android:textSize="35sp" />
</LinearLayout>

SharedPreferenceActivity.java

package com.vipul.p6;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class SharedPreferenceActivity extends AppCompatActivity {

    EditText nameEditText;
    Button saveBtn, showBtn;
    TextView savedNames;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preference);

        nameEditText = findViewById(R.id.nameEditText);
        saveBtn = findViewById(R.id.saveBtn);
        showBtn = findViewById(R.id.showBtn);
        savedNames = findViewById(R.id.savedName);

        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameEditText.getText().toString();
                SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("username", name);
                editor.apply();
                Toast.makeText(getApplicationContext(), "Name saved!", Toast.LENGTH_SHORT).show();
                savedNames.setText(name);
            }
        });

        showBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
                String savedName = sharedPreferences.getString("username", "No name saved");
                Toast.makeText(getApplicationContext(), "Saved Name: " + savedName, Toast.LENGTH_SHORT).show();
                savedNames.setText(savedName);
            }
        });
    }
}

Detailed Explanation of the Code:

XML Layout:

  • TextView shows the app heading.
  • EditText is where the user can input their name.
  • Save Name Button saves the input into SharedPreferences.
  • Show Saved Name Button retrieves and displays the saved name.
  • savedName TextView displays the current stored name.

Java Code:

  • When the Save button is clicked, it stores the name using SharedPreferences.Editor and displays a Toast confirmation.
  • When the Show button is clicked, it retrieves the name from SharedPreferences and displays it both as a Toast and in the TextView.

What is SharedPreferences in Android?

SharedPreferences is a lightweight way to store key-value data in Android. It is perfect for saving simple data like user settings, login info, or preferences that persist even after the app is closed.

Key Features of SharedPreferences:

  • Stores data persistently (even after the app is closed).
  • Data is stored in XML format in the app’s private directory.
  • Only suitable for small key-value data storage.
  • Can be easily accessed and modified.

How to use SharedPreferences:

  1. Create or access SharedPreferences using getSharedPreferences("YourPrefName", MODE_PRIVATE).
  2. Use Editor to save data using putString(), putInt(), etc.
  3. Apply or commit changes using editor.apply().
  4. Retrieve data using getString(), getInt(), etc.

Conclusion:

SharedPreferences is an essential tool for Android developers to store small bits of data persistently. This example provides a very simple and practical demonstration for beginners to understand and implement SharedPreferences in their own projects.