Save preferences with SharedPreferences

SharedPreferences is a an easy way to store user preferences to a file in Android. SharedPreferences are saved to file so they’re available after application and device restarts. The nice thing about using SharedPreferences is that all of the work is handled by the SharedPreferences class itself, so using it requires minimal effort from the developer. It also supports the most common data types (booleans, ints, floats, longs, strings and string sets.) which makes it a handy tool for every developer.

Basics

As said earlier the SharedPreferences is implemented by class with the same name. This class breaks down to two parts, SharedPreferences and SharedPreferences.Editor. SharedPrefences handles preference reading and Editor the preference writing.

To access a SharedPreference instance, you first need to create it. the constructor requires a name and the opening mode as parameters. The name just implies the file name that is used when the preferences are store and the mode tells who can access the preferences file. More info about the available modes is available from Context.getSharedPreferences Javadoc.

Once you have the SharedPreference instance you can read preference values by calling the appropriate method and giving a key for the preference. Writing the prefences is achieved by first calling edit() which returns an Editor instance and then putting the changes with the available putXXX() methods. One thing to note here is that the changes are not saved until you call apply() (API level 9 onwards) or commit().

The example below show how you can read and write SharedPreferences.

Example

package com.caphal.android.sharedpreferencestutorial;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class SharedPreferencesActivity extends Activity {

    private static final String KEY = "key";

    private SharedPreferences preferences;

    private EditText textField;

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

        preferences = getSharedPreferences("preferences", Context.MODE_PRIVATE);
        textField = (EditText) findViewById(R.id.editText);
    }

    @SuppressLint("NewApi")
    public void onWriteClick(View view) {

        Editor editor = preferences.edit();
        editor.putString(KEY, textField.getText().toString());

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
            editor.apply();
        } else {
            // This call is synchronous and should be done in a background
            // thread
            editor.commit();
        }
    }


    public void onReadClick(View view) {

        String text = "Saved value is " + preferences.getString(KEY, null);

        Toast.makeText(this, text, Toast.LENGTH_LONG).show();
    }

}

Screenshots

Read 1 Read 2

Source code

Source code for the whole example project is available here

Further reading

Comments

comments powered by Disqus