Android SharedPreferences allows us to store private primitive application data in the form of key-value pair.

  • Android stores shared preference settings as XML file in shared_prefs folder under DATA/data/[application package] directory. The DATA folder can be obtained by calling Environment.getDataDirectory() (usually it is /data).
  • SharedPreferences is application specific, i.e.) the data is lost when you perform one of the options,
  • once you uninstall the application
  • once you clear application data (through Settings)

Java File ActivityMain.java : –

package safal.bhatia.sharedpreferencesexample;
import android.app.Activity;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Activity sActivity;
    String saf = "Safal Bhatia";
    TextView text_view;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sActivity = MainActivity.this;
        text_view = (TextView)findViewById(R.id.text_view);
        // Store Data in SharedPreferences
       
SharedPreferences pref = sActivity.getSharedPreferences("MyPref", 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("Email",saf);
        editor.commit();

        //Get data from SharedPreferences
       
SharedPreferences pref1 = sActivity.getSharedPreferences("MyPref", 0);
        String get_data =  pref1.getString("Email","");
        text_view.setText(get_data);
    }

}

Xml File activity_main: –

<?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:gravity="center"
    android:layout_height="match_parent"
    tools:context="safal.bhatia.sharedpreferencesexample.MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/text_view" />
</LinearLayout>