Shared Preference

Android provides many ways of storing data, one of which is shared preference. It uses key-value architecture to store data. SharedPreferences values will persist across user sessions. Data in shared preferences will be persistent even though user closes the application. Shared preference is application specific, that’s the reason data gets lost on uninstalling or clearing the application data. To read the data from the store we have to know the key of the data. This makes reading the data very easy. But as easy as it is to store a small amount of data as difficult it is to store and read large structured data as we need to define key for every single data, furthermore we cannot really search within the data except you have a certain concept for naming the keys. So it is not advised to use shared preference for storing large amount of data.

To use shared preference, call method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences. It contains two parameter, the first parameter is name and the second is mode, see below for reference.

SharedPreferences sharedpreferences = getSharedPreferences(“MyPref”, Context.MODE_PRIVATE);

Now to save something, we need to use SharedPreferences.Editor class. Call the edit method of SharedPreference instance and it will return it in an editor object.

Editor editor = sharedpreferences.edit();

Using editor, we can store data. For reference, check below code.

editor.putBoolean("BooleanValue ", true);
editor.putInt("IntegerValue ", "int value");
editor.putFloat("FloatValue", "float value");
editor.putLong("LongValue", "long value");
editor.putString("StringValue", "string value");

And finally we need to call commit() method to commit the changes.


Now to retrieve data from shared preferences, we use the object of SharedPreferences as shown below. The first argument is key and second argument is a value to be return if the key is not found.

sharedpreferences.getBoolean("BooleanValue ", null);
sharedpreferences.getInt("IntegerValue ", null);
sharedpreferences.getFloat("FloatValue", null);
sharedpreferences.getLong("LongValue", null);
sharedpreferences.getString("StringValue", null);

To delete value from shared preferences, we will use editor and then we will commit to reflect the changes. Below is the code for this. We need to pass the key as argument.

editor.remove("BooleanValue ");

Using editor we can clear the data in the shared preference. The method is clear().