Writing and Reading from SharedPreferences

SharedPreferences class allows you to save and retrieve primitive data types in key-value pairs. The data saved using SharedPreferences will be available even after your application is killed. This capability makes SharedPreferences suitable in different situations when user settings needs to be saved for example, or store data that can be used in different activities.
The data types that can be saved are booleans, floats, ints, longs, and strings.

To get an instance of SharedPreferences use the getSharedPreferences(String, int) method. The method takes 2 parameters: the name of the preference settings and the mode. (0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions)

To write values:

  1. Call edit() to get a SharedPreferences.Editor instance
  2. Add values with methods such as putInt() and putString().
  3. Call commit() to save values.

To read values use such methods as getString() and getInt() of SharedPreferences instance.

Here’s a simple usage of SharedPreferences class:

public class SharedPrefsActivity extends Activity {

  public static final String PREFS_NAME = "MyApp_Settings";

  public void onCreate(Bundle savedInstanceState) {

     SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

     // Writing data to SharedPreferences
     Editor editor = settings.edit();
     editor.putString("key", "some value");

     // Reading from SharedPreferences
     String value = settings.getString("key", "");
     Log.d(TAG, value);

Please visit the Android Tutorials page for more tutorials.