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.


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.



import android.annotation.SuppressLint;
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;

    protected void onCreate(Bundle savedInstanceState) {

        preferences = getSharedPreferences("preferences", Context.MODE_PRIVATE);
        textField = (EditText) findViewById(;

    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) {
        } else {
            // This call is synchronous and should be done in a background
            // thread

    public void onReadClick(View view) {

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

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



Read 1 Read 2

Source code

Source code for the whole example project is available here

Further reading


comments powered by Disqus