How to use SharedPreferences in Android

In Android, one way to save data from withing application is with the help of SQLite database. But sometimes, we don’t need complexities of SQLite and we can save data in SharedPreferences. They are usually used to save user preferences on some settings of application or Activity.

When we want to save some data which is accessible throughout the application, one way to do is to save it in global variable. But it will vanish once the application is closed. Another and recommended way is to save in SharedPreference. Data saved in SharedPreferences file is accessible throughout the application and persists even after the application closes or across reboots.

SharedPreferences saves the data in key-value pair and can be accessed in same fashion.

Fetch shared preferences

getSharedPreferences() method can be used to initialize shared preferences. An editor is required to edit and save data in shared preference.

SharedPreferences sharedPreferences = getActivity().getApplicationContext().getSharedPreferences("SamplePref",0);

Editor editor = sharedPreferences.edit();

 

Save data in shared preference

Data can be used with the help of editor. All major primitive data types are supported. After making changes to shared preference file, a call to commit() should be made in order to write those changes.

editor.putString("name", "Android"); // key: name, value: Android

editor.putInt("count", 5); // key: count, value: 5

editor.commit(); // writing changes to file

 

Retrieve data from shared preference

Data can be retrieved from shared preference (not from editor) by calling getString() for String, getInt() for Integer and so on.

// returns value for this key or if not found it will return null
sharedPreferences.getString("name", null);


// returns 0 if value not found

sharedPreferences.getInt("count", 0);

 

Deleting data from shared preference

You can call remove() method on editor to remove a particular key-value from shared preference. To delete all the data, you can call clear() method on editor. Of course, you need to call commit() after making desired changes.

// this removes the value for key- count

editor.remove("count");

editor.commit();

// this removes all the data for this shared preference file

editor.clear();

editor.commit();

Reference: http://developer.android.com/reference/android/content/SharedPreferences.html


I am a Developer. My motto: "Language is not a barrier" http://hayageek.com
All posts by Ravishanker Kusuma