Home > Researches > Writing and Reading from SharedPreferences

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";

  @Override
  public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);

     SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

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

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

Please visit the Android Tutorials page for more tutorials.

About these ads
  1. azael05x
    April 1, 2012 at 5:46 am

    Hmmm… Nice Blog.. Keep it up :)

  2. April 2, 2012 at 8:32 am

    Hey :),

    Nice Blog!! :)

    • April 2, 2012 at 4:43 pm

      Thanks, feel free to get the most of it. :)

  3. Israel
    April 19, 2013 at 9:38 am

    can we use put string + commit first and then in the last of the programcan we use get string+commit?

  1. April 7, 2013 at 1:57 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 507 other followers

%d bloggers like this: