DEV Community

Victordgrandis
Victordgrandis

Posted on

How to store data in SharedPreferences

I will be showing a simple but very useful way to store simple data for preferences on your Android app.
For that i'll be using SharedPreferences, which is in Android since the API v1, so there're no restrictions of versions for using it.
SharedPreferences lets you store key-value pairs of primitive data types, and read them in any place of your app, being stored in persistent XML files.

Storing preferences

First, of course, we have to import the interface:

import android.content.SharedPreferences;
Enter fullscreen mode Exit fullscreen mode

Then, we can use it:

SharedPreferences prefs = this.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("folder", folder);
editor.putString("route", route);
editor.putString("name", name);
editor.putLong("modified", modified);
editor.apply();
Enter fullscreen mode Exit fullscreen mode

Here what i'm doing is starting a new preference store under the key "MyPrefs", if i don't have one already its created.
On the second line i'm initializing a SharedPreferences editor, which allow us to modify the prefs object using the methods putString(), putLong(), putInt(), putFloat(), putBoolean() or putStringSet(). According, obviously, to the type of values you want to store. In my example i only need to store a few strings and a long value.

After adding the values i needed, i call the apply() method, which store the modified SharedPreference objects in the persistent XML files.
The Editor provides two methods to commit the changes, one is the used above, and the other one is commit(), the main differences are that apply() is asynchronous and don't return any value. If you need to know the result of the transaction you can use commit() that returns a boolean with the status of the write in the persistent storage.

Reading preferences

The reading process is even easier:

SharedPreferences prefs = this.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String folder = prefs.getString("folder", null);
String route = prefs.getString("route", null);
String name = prefs.getString("name", null);
long modifiedDate = prefs.getLong("modified", 0);
Enter fullscreen mode Exit fullscreen mode

Here the only new methods are the getters, that correspond to each put that i enumerate before. The only difference is in the second argument, that is a default value for the variable to take if the key is empty in the stored preferences.

Conclusion

This is a very straight forward way to store some persistent data like user preferences or some state of the app without having to manage a database or something more complex.

Oldest comments (0)