Saving data in shared preferences in Android

SharedPreferences is an interface for storing and retrieving data in Android. It stores the data in key-value pairs. It supports boolean, int, long, float, String, and Set. For complex data, you can convert object into a json string and store the json string in SharedPreferences.

getPreferences() is a method defined in the Acitivty class for retrieving the SharedPreference object. If you are not in an Activity class, you will have to get the activity and then call the getPreferences on that activity. For example, in a Fragment, you can call getActivity().getPreferences().

Saving the string “Hey, how are you doing?” with the key “greeting”. For other data types, there are putInt(), putLong(), putFloat(), putBoolean() and putStringSet().

SharedPreferences preferences = getPreferences(this.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("greeting", "Hey, how are you doing?");
editor.commit();

Retrieving the String associated with the key “greeting”. For other data types, there are getInt(), getLong(), getFloat(), getBoolean() and getStringSet().

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String greeting = sharedPreferences.getString("greeting", "");

Delete the data associated with the key “greeting”.

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("greeting");
editor.commit();

Clear all data in the Shared Preferences.

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();

Search within Codexpedia

Custom Search

Search the entire web

Custom Search