Skip to main content

Android Shared Preferences

SharedPreferences are used to store small amount of information in the form of key-value pair.
Let's take an example to see how SharedPreferences work-

1. Create a new android project.
2. Open activity_main.xml and add two editable fields and two buttons.
<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="vertical"
    tools:context="com.gunjan.andriodcodesnippets.MainActivity"
    android:gravity="center_vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_name"
        android:hint="Name"
        android:textSize="25sp"
        android:layout_marginBottom="10dp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_password"
        android:hint="Password"
        android:textSize="25sp"
        android:layout_marginBottom="10dp"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="center">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/bt_save"
            android:text="Save"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/bt_show"
            android:text="Show"
            />
    </LinearLayout>
</LinearLayout>
3. Create a new class PreferencesHelper.java and type the following code-
public class PreferencesHelper{

    private SharedPreferences sharedPreferences;
    private Editor editor;
    private final static String PREFERENCES="mySettings";
    private final static String DEFAULT_VALUE="none";

    PreferencesHelper(Context context){
        this.sharedPreferences=context.getSharedPreferences(PREFERENCES,Context.MODE_PRIVATE);
        this.editor=sharedPreferences.edit();
    }

    public String GetPreference(String key){
        return sharedPreferences.getString(key,DEFAULT_VALUE);
    }

    public void SetPreference(String key,String value){
        editor.putString(key,value);
        editor.commit();
    }
}
4. Open MainActvity.java and type the following code-
public class MainActivity extends AppCompatActivity {

    PreferencesHelper preferencesHelper;
    Button myButtonSave,myButtonShow;
    EditText myName,myPassword;
    private final static String NAME="name";
    private final static String PASSWORD="password";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        preferencesHelper=new PreferencesHelper(this);

        myButtonSave=(Button)findViewById(R.id.bt_save);
        myButtonShow=(Button)findViewById(R.id.bt_show);
        myName=(EditText)findViewById(R.id.et_name);
        myPassword=(EditText)findViewById(R.id.et_password);

        myButtonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name=myName.getText().toString();
                String password=myPassword.getText().toString();

                //Save data in SharedPreferences
                preferencesHelper.SetPreference(NAME,name);
                preferencesHelper.SetPreference(PASSWORD,password);

                //Clear text fields
                myName.setText("");
                myPassword.setText("");
            }
        });
        myButtonShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Retrieve data from SharedPreferences
                String name=preferencesHelper.GetPreference(NAME);
                String password=preferencesHelper.GetPreference(PASSWORD);

                //Set data in text fields
                myName.setText(name);
                myPassword.setText(password);
            }
        });
    }
}
5. Run the project, enter details and click on save button, the values will be saved in shared preferences. Now, click on show button and you will see the text you have saved. 

Comments

Popular Posts