ZOFTINO.COM android and web dev tutorials

Saving Key Value Pairs in Android Using SharedPreferences API

SharedPreferences API provides framework to read and write key value pairs in Android. SharedPreferences API stores data in a file on the device. SharedPreferences supports primitive type data.

The first step in using SharedPreferences API is to get reference to SharedPreferences object. There are two ways to get SharedPreferences object. If you want to save data in activity specific file, use activity’s getPreferences() method to get SharedPreferences object. This way you don’t need to pass file name, activity’s default shared preference file is used.

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

If you want to save data to a file which needs to be shared among application components, then get SharedPreferences object using context’s getSharedPreferences() method. It takes two parameters, first one is file name and second parameter indicates file mode such as MODE_PRIVATE and MODE_APPEND.

By default file is created as private meaning only app creating it can access it. MODE_APPEND indicates that data should be appended to existing content of the file instead of erasing it when file is being modified.

Note that MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE are deprecated due to security reasons. If you want to share data with other apps, use content providers or services. Mode constants can be found in Context class.

Context context = getApplicationContext();

SharedPreferences
 sharedPref = context.getSharedPreferences(
        getString(R.string.coupon_pref), Context.MODE_PRIVATE);

Write to SharedPreference File

To write to shared preference file, you need to use SharedPreferences.Editor object. You can get this object by calling edit() method on SharedPreferences object. After modification is done, you need to call commit() to save the changes.

SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(getString(R.string.coupon_type), coupon_types.getText().toString());
editor.putString(getString(R.string.discount_type), discount_types.getText().toString());
editor.putBoolean(getString(R.string.cashback), Boolean.valueOf(cashback.getText().toString()));

editor.commit();

Read Data from SharedPreferences

You can check for existence of a key in SharedPreferences by calling contains() method passing key name to it. To get value of a key, you need to call corresponding value type method passing key name, for example to get an int value, you need to call getInt() method.

        String d_type = sharedPref.getString(getString(R.string.discount_type), defaultValue); 

Shared Preference Change Listener

You can implement SharedPreferences.OnSharedPreferenceChangeListener and register the listener by calling registerOnSharedPreferenceChangeListener(). This listener is notified when there is a change to shared preference.

Saving Key Value Pairs Example

Activity

 package com.zoftino.content;

        import android.content.Context;
        import android.content.SharedPreferences;
        import android.os.Bundle;
        import android.support.v7.app.AppCompatActivity;
        import android.view.View;
        import android.widget.EditText;
        import android.widget.Toast;

public class SharedPreferenceActivity extends AppCompatActivity {

    private SharedPreferences sharedPref;

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

        Context context = getApplicationContext();
        sharedPref = context.getSharedPreferences(
                getString(R.string.coupon_pref), Context.MODE_PRIVATE);
        sharedPref.registerOnSharedPreferenceChangeListener(sharedPrefListener);
    }

    public void savePreference(View view) {
        EditText coupon_types = (EditText) findViewById(R.id.c_type);
        EditText discount_types = (EditText) findViewById(R.id.d_type);
        EditText cashback = (EditText) findViewById(R.id.cashback_offer);

        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString(getString(R.string.coupon_type), coupon_types.getText().toString());
        editor.putString(getString(R.string.discount_type), discount_types.getText().toString());
        editor.putBoolean(getString(R.string.cashback), Boolean.valueOf(cashback.getText().toString()));

        editor.commit();
    }

    public void getPreference(View view) {
        String defaultValue = "all";
        String c_type = sharedPref.getString(getString(R.string.coupon_type), defaultValue);
        String d_type = sharedPref.getString(getString(R.string.discount_type), defaultValue);

        boolean cashback_defalut = true;
        boolean cashback_val = sharedPref.getBoolean(getString(R.string.cashback), cashback_defalut);

        EditText coupon_types = (EditText) findViewById(R.id.c_type);
        coupon_types.setText(c_type);

        EditText discount_types = (EditText) findViewById(R.id.d_type);
        discount_types.setText(d_type);

        EditText cashback = (EditText) findViewById(R.id.cashback_offer);
        cashback.setText("" + cashback_val);
    }

    private SharedPreferences.OnSharedPreferenceChangeListener sharedPrefListener =
            new SharedPreferences.OnSharedPreferenceChangeListener() {

                @Override
                public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
                    Toast.makeText(getApplicationContext(), "Shared Preference Listener Change is : " + s + " " + sharedPreferences.toString(),
                            Toast.LENGTH_SHORT).show();
                }
            };
}
 

Activity layout

 <?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_sf"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.zoftino.content.SharedPreferenceActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <TextView android:id="@+id/c_type_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:padding="10dp"
            android:textSize="15sp"
            android:text="Interested Coupon Types">
        </TextView>
        <EditText
            android:id="@+id/c_type"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true" >
        </EditText>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <TextView android:id="@+id/d_type_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:padding="10dp"
            android:textSize="15sp"
            android:text="Interested Discount Types">
        </TextView>
        <EditText
            android:id="@+id/d_type"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true" >
        </EditText>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <TextView android:id="@+id/cashback_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:padding="10dp"
            android:textSize="15sp"
            android:text="View Cashback Offers?">
        </TextView>
        <EditText
            android:id="@+id/cashback_offer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true" >
        </EditText>
    </LinearLayout>
    <Button
        android:id="@+id/write_pref"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="savePreference"
        android:text="SAVE PREFERENCE"></Button>
    <Button
        android:id="@+id/read_pref"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="getPreference"
        android:text="GET PREFERENCE"></Button>
</LinearLayout>