Android - Shared Preferences Tutorial

Shared Preferences Tutorial

1) Shared Preferences allow you to save and retrieve data in the form of key,value pair.
2) You cannot share preferences outside of the package.
3) Preferences are stored as groups of key/value pairs.


Creating shared preferences 

SharedPreferences pref = getSharedPreferences(“MyPreferences”, Context.MODE_PRIVATE);

- The first parameter is the key and the second parameter is the MODE.

- You can save something in the sharedpreferences by using SharedPreferences.Editor class.

SharedPreference.Editor editor = pref.edit();


SharedPreferences.Editor Methods :

1) clear() : It will remove all values from the editor.

2) remove(String key) : It will remove the value whose key has been passed as a parameter.

3) putString(String key, String value) : It will save a String value in a preference editor.

4) putLong(String key, long value) : It will save a long value in a preference editor.

5) putInt(String key, int value) : It will save a integer value in a preference editor.

6) putFloat(String key, float value) : It will save a float value in a preference editor.

7) commit() : It will save the changes in SharedPreferences.


Example 

// ----- Create SharedPreferences -----
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 

SharedPreferences.Editor editor = pref.edit();

// ----- Storing data as KEY/VALUE pair -----
editor.putBoolean("key_name1", true);           // Saving boolean - true/false
editor.putInt("key_name2", "int value");        // Saving integer
editor.putFloat("key_name3", "float value");    // Saving float
editor.putLong("key_name4", "long value");      // Saving long

editor.putString("key_name5", "string value");  // Saving string

// Save the changes in SharedPreferences

editor.commit(); // commit changes

// ----- Get SharedPreferences data -----
// If value for key not exist then return second param value
pref.getBoolean("key_name1", null);         // getting boolean
pref.getInt("key_name2", null);             // getting Integer
pref.getFloat("key_name3", null);           // getting Float
pref.getLong("key_name4", null);            // getting Long

pref.getString("key_name5", null);          // getting String

// ----- Deleting Key value from SharedPreferences -----
editor.remove("key_name3"); // will delete key key_name3

editor.remove("key_name4"); // will delete key key_name4

// Save the changes in SharedPreferences

editor.commit(); // commit changes

// ----- Clear all data from SharedPreferences -----
editor.clear();

editor.commit(); // commit changes


Comments

Post a Comment

Popular posts from this blog

Android - Set cursor drawable programmatically

Create custom button in android