Local data Saved using Sharedpreference

The Android platform gives developers multiple ways to store data in local memory with each method having it’s advantages and disadvantages and we’ll discuss the different data storage techniques available to Android developers and along with sample code to get you started also to refresh your memory.

Shared Preferences

we should use this to save primitive data in key-value pairs and we have a key and it must be a String and the corresponding value for that key and will be one of: boolean ()true/false), float, int, long or string and Internally, the Android platform stores an app’s Shared Preferences in an xml file in a private directory and the app can have multiple Shared Preferences files. Generally we will want to use Shared preferences to store application preferences.

Using Shared Preferences

To store data using shared preferences we must first get a SharedPreferences object and there can be two Context methods that can be used to retrieve a SharedPreferences object.

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);

for when our app will have a single preferences file, and

SharedPreferences sharedPreferences = getSharedPreferences(fileNameString, MODE_PRIVATE);

for when our app could have multiple preferences files and if you prefer to name your SharedPreferences instance.

Finally, please make sure to call Editor’s commit() method after putting or removing values. If we don’t call commit, our changes will not be persisted.

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(keyString, valueString);

For your sample app, you will allow the user specify a SharedPreferences filename and If the user specifies a name and we request for the SharedPreferences having that name and if not, you will request for the default SharedPreference object.

Note that there is no function to get a list of all SharedPreferences files stored by your app and If we are going to store more than one SharedPreferences file, we should either have a static list, or be able to get the SharedPreferences name and On the other hand, we can save your SharedPreferences names in the default SharedPreferences file and To store user preferences, consider using a PreferenceFragment, although they both use Shared Preferences to manage the user preference.

Subscribe Now