Android - Store data using SharedPreferences API

By xngo on February 27, 2019

Overview

Android provides different ways to store data such as using a SQLite database or SharedPreferences API. If you need a database, see Store and retrieve data from SQLite in Android. For this tutorial, we are going to focus on SharedPreferences API.

SharedPreferences stores its data in key-value pairs fashion. It is very simple to use. You only need:

  • To give a unique name for your preference.
  • Set your preference mode: PRIVATE or SHARED.
  • Load your preference's editor to write, read and delete data.

Basic operations on SharedPreferences API

public class SharedPref {
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
 
    public SharedPref(Context context){
        this.preferences = context.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
        this.editor = this.preferences.edit();
    }
 
    public void add(String key, String value){
        this.editor.putString(key, value);
        this.editor.commit();
    }
 
    public String get(String key){
        return this.preferences.getString(key, "");
    }
 
    public void remove(String key){
        this.editor.remove(key);
        this.editor.commit();
    }
 
    public Map<String, ?> getAll(){
        return this.preferences.getAll();
    }
}

Note: Don't forget to commit after you are done with the editor. Otherwise, changes will not be saved.

Using SharedPref class

public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        LinearLayout linearLayout = this.findViewById(R.id.main_linearlayout);
 
        SharedPref sharedPref = new SharedPref(this);
 
        // Add preference.
        Date now = new Date();
        sharedPref.add(now.getTime()+"", "Some value");
 
        // Display all preferences.
        Map<String, ?> allFavorites = sharedPref.getAll();
        for (Map.Entry<String, ?> entry : allFavorites.entrySet()) {
            String text = String.format("key=%s, value=%s", entry.getKey(),
                                                            entry.getValue().toString());
            TextView textView = new TextView(this);
            textView.setText(text);
            linearLayout.addView(textView);
        }
    }
}

Output

SharedPreferences screenshot

Github

  • https://github.com/xuanngo2001/android-sharedpreferences-basic

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.