Simple use of Shared Preference Android

Here is a very simple implementation of Shared Preferences in Android Development.

Step 1:   Create a Shared preferences object prefs from file “com.sagar.prefs”.

SharedPreferences prefs = getSharedPreferences(“com.sagar.prefs”, Context.MODE_PRIVATE );// this code is enough for creating the file and getting its object.

 

Step 2. Write some value in the shared preferences

copy this method in your code:

private void setPreferences(String key_str, String value_str){

           Editor editor = prefs.edit();
           editor.putString(key_str, value_str); 
           editor.commit();
}

and use this to save any value in shared preferences  setPreferences(“name”, “value”); // this will save the value for this name.

 

Step 3: Get data from shared preferences:

String str = prefs.getString(“name”, “d”);  // where d is the default value which will be return if there is no value for the given “name” in the shared preferences.

 

Advertisements

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

%d bloggers like this: