Android: Using Shared Preferences for Storing Data

The SharedPreferences API in Android Content(android.content.sharedpreferences) is the easiest and most convenient way to store simple data types like boolean, int and float as key-value pairs.

The data that you store through this method is private to a given application and is not visible to other applications (even those that access the particular application’s storage). The data that you store in SharedPreferences persists even after the application session is destroyed making it available for any future sessions of the application.

The following steps provide a example demo of its usage.

Storing Data

Step 1. Import Module

import android.content.SharedPreferences;

Step 2.Add a Variable declaration/ Create Preference File

public static final String PREFERENCES_FILE_NAME = "MyAppPreferences";

Step 3. Retrieve a handle to filename (using getSharedPreferences)

SharedPreferences settingsfile= getSharedPreferences(PREFERENCES_FILE_NAME,0);

Step 4. Open Editor and Add key-value pairs

SharedPreferences.Editor myeditor = settingsfile.edit(); 
myeditor.putBoolean("playaudio", true); 
myeditor.putFloat("volume", 0.7)
myeditor.putInt("border", 2)
myeditor.putLong("size", 12345678910L)
myeditor.putString("name", "bond")

Don’t forget to commit/save using myeditor.commit() as shown above.

Retrieving Data

SharedPreferences mysettings= getSharedPreferences(PREFERENCES_FILE_NAME, 0);
playAudio = mysettings.getBoolean("playaudio", false); 
//returns value for the given key. 
//second parameter gives the default value if no user preference found
// (set to false in above case)
volume = mysettings.getFloat("volume", 0.5) 
//0.5 being the default value if no volume preferences found
// and similarly there are get methods for other data types