techStackGuru

Shared Preferences in Android


The Shared Preferences feature lets you store and retrieve data as a key-value pair. Since they are internal storage, no external database is required to store them.

You have to call getSharedPreferences() in order to retrieve the shared preferences, which returns an instance of SharedPreference pointing to the file containing the values of preferences.

SharedPreferences sharedpref = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

The app data folder stores the shared preferences in an xml file

/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml

or the default preferences at:

/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml

In the example below, we will see how to store values in shared preferences and retrieve them back in another activity.

MainActivity.java

package com.example.techstackguru;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    public static final String MyPREFERENCES = "MyPrefs" ;
    public static final String Name = "nameKey";
    SharedPreferences sharedpreferences;
    EditText editText;
    Button button;

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

        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        editText = findViewById(R.id.editText);
        button = findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String value  = editText.getText().toString();
                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString(Name, value);
                editor.commit();

                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);
            }
        });
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat 
    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"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="50dp"/>
   
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"
        android:layout_gravity="center" />

</androidx.appcompat.widget.LinearLayoutCompat>

Below is SecondActivity which we will use to fetch the shared preference value.

SecondActivity.java

package com.example.techstackguru;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class SecondActivity extends AppCompatActivity {

    public static final String MyPREFERENCES = "MyPrefs" ;
    SharedPreferences sharedpreferences;
    public static final String Name = "nameKey";
    TextView textView;

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

        textView = findViewById(R.id.textview);
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        String response = sharedpreferences.getString(Name, "");
        textView.setText(response);
    }
}

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat 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"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textview"
        android:gravity="center"
        android:textStyle="bold"
        android:text="sfsdf"
        android:textSize="26sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="50dp"/>

</androidx.appcompat.widget.LinearLayoutCompat>

Give permission in AndroidManifest file for SecondActivity

AndroidManifest.xml

<activity android:name=".SecondActivity"/>

After successfully entering both the above mentioned codes in their respective files, you will be ready to launch your project and view the output. By using the codes we have shown, your output would look like the following illustration:

Output
rating-bar-1
rating-bar-1

previous-button
next-button