SharedPreferences PDF - Android Development Tutorial
Document Details

Uploaded by DeliciousNovaculite7475
Wissam H.
Tags
Summary
This document is a presentation on Android's SharedPreferences, a mechanism for storing simple data like user preferences. It covers how to read and write data using examples and available methods like putString and commit, explaining use cases, such as saving application settings.
Full Transcript
SharedPreferences Wissam H. What are Shared Preferences ? A simpler way (then SQLite) for storing data of an application. Suited to store user’s personal settings of an application Data is saved and retrieved in the form of (key, value) pair. SharedPreferences API provides a set of me...
SharedPreferences Wissam H. What are Shared Preferences ? A simpler way (then SQLite) for storing data of an application. Suited to store user’s personal settings of an application Data is saved and retrieved in the form of (key, value) pair. SharedPreferences API provides a set of methods for reading and writing primitive data (String, int, long, float and boolean). How to use Shared Preferences ? to use shared preferences, we have to call method getSharedPreferences() on Activity context. SharedPreferences getSharedPreferences(PrefFileName, mode); Each activity have a default SharedPreference which can be accessed using : PreferenceManager.getDefaultSharedPreferences(context) Reading Data from Shared Preferences Call one of the getXXX() methods using SharedPreferences instance. Example : settings = context.getSharedPreferences(PrefFileName, Context.MODE_PRIVATE); text = settings.getString(“mykeyname1”, null); Simularly use : getFloat, getInt, getLong, getBoolean The second parameter is the default value to be returned in case preference key does not exist (or null) Writing Data to Shared Preferences To save something in a sharedpreferences, we need to get its “Editor” object to put key-value pairs. Editor process put operations when receiving “commit” call. Example : settings = context.getSharedPreferences(PrefFileName, Context.MODE_PRIVATE); Editor editor = settings.edit(); editor.putString(" mykeyname1 ", "value"); editor.commit(); Similarly use Editor methods : putFloat, puttInt, putLong, putBoolean (followed by a “commit” call). Other Editor methods: clear( ) : Mark in the editor to remove all values from the preferences. Once commit is called, the only remaining preferences will be any that you have defined in this editor (before or after clear). Note that when committing back to the preferences, the clear is done first, regardless of whether you called clear before or after put methods on this editor remove(String key) : Mark in the editor that a preference value should be removed, which will be done in the actual preferences once commit() is called.