Android - Store data using SharedPreferences API

By xngo on February 27, 2019


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);
    public String get(String key){
        return this.preferences.getString(key, "");
    public void remove(String key){
    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 {
    protected void onCreate(Bundle savedInstanceState) {
        LinearLayout linearLayout = this.findViewById(;
        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(),
            TextView textView = new TextView(this);


SharedPreferences screenshot



About the author

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