Here is the text rewritten in paragraphs without subheadings:
Shared Preferences is a simple and efficient way to store small amounts of data in an Android application. It allows developers to store primitive types, such as booleans, floats, ints, longs, and strings, in a key-value pair format. Thi...
Here is the text rewritten in paragraphs without subheadings:
Shared Preferences is a simple and efficient way to store small amounts of data in an Android application. It allows developers to store primitive types, such as booleans, floats, ints, longs, and strings, in a key-value pair format. This data is stored locally on the device and is accessible only by the app that created it.
Shared Preferences is useful for storing user preferences, settings, or app state. It persists data across app restarts and device reboots, making it ideal for storing data that needs to be retained even after the app is closed. Additionally, Shared Preferences is a simple and lightweight solution compared to databases or files, making it a great choice for small amounts of data.
To use Shared Preferences, you need to get a SharedPreferences instance using either getSharedPreferences() or getPreferences(). The former creates a new or existing shared preference file with a specified name, while the latter creates a new or existing shared preference file with the activity's class name. Once you have a SharedPreferences instance, you can use edit() to get an Editor object, which allows you to put values using methods like putBoolean(), putFloat(), and putString(). Finally, you commit changes using commit() or apply().
There are two types of Shared Preferences: getSharedPreferences() and getPreferences(). The former allows you to specify a name for the shared preference file, while the latter uses the activity's class name as the file name. Both methods create a new file if it doesn't exist or open an existing one if it does. When using Shared Preferences, it's essential to follow best practices. Use a consistent naming convention for shared preference files to avoid confusion. Keep shared preference files private to the app to prevent other apps from accessing your data.
Avoid storing sensitive data or large amounts of data, as Shared Preferences is not designed for such purposes. Finally, use apply() instead of commit() for asynchronous saving. Here's an example of how to use Shared Preferences: SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean("isDarkMode", true); editor.putString("username", "JohnDoe"); editor.apply(); This code creates a shared preference file named "MyPrefs" and stores two values: a boolean indicating dark mode and a string for the username.
Shared Preferences is a powerful tool for storing small amounts of data in Android applications. By following best practices and using it correctly, developers can create robust and efficient apps that retain data even after app restarts and device reboots. With its simple and lightweight design, Shared Preferences is an ideal solution for many use cases. It's easy to implement and integrates seamlessly with Android's architecture, making it a popular choice among developers.
Size: 127.46 KB
Language: en
Added: Aug 04, 2024
Slides: 21 pages
Slide Content
SHARED PREFERENCES Creating, Saving, And Retrieving Shared Preferences BY, ABDUL HASEEB T ROLL NO : 101
Shared Preferences Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage. Shared Preferences can be thought of as a dictionary or a key/value pair. Shared Preferences class provides APIs for reading, writing and managing this data In order to use shared preferences ,call a method getSharedPreferences() that returns a shared preference instance pointing to the file that contains the value of preferences Syntax: public abstract SharedPreferences getSharedPreferences (String name, int mode) SharedPreferences sharedPreferences = getSharedPreferences(MyPreferences, MODE_PRIVATE);
Shared Preferences This method takes two arguments, first being the name of the SharedPreference (SP) file and other is the context mode that we want to store our file in. MODE_PUBLIC will make the file public which could be accessible by other applications in the device MODE_PRIVATE keeps the files private and secure user’s data. ◦ MODE_APPEND is used while reading the data from SP file.
Nested classes of Shared Preferences SharedPreferences.Editor: Interface used to write(edit) data in SP file. Once editing has been done, one must commit() or apply() the changes made to the file. SharedPreferences.OnSharedPreferenceChangeListener(): Called when a shared preference is changed, added, or removed. This may be called even if a preference is set to its existing value. This callback will be run on your main thread.
To Write Data in Shared Preferences use SharedPreferences.Editor class Syntax: SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString( keyString , valueString ) editor.commit ();
To read data use shared preference methods such as getAll (): This method is used to retrieve all values from the preferences. ◦ getBoolean (String key, boolean defValue ): This method is used to retrieve a boolean value from the preferences. ◦ getFloat (String key, float defValue ): This method is used to retrieve a float value from the preferences. ◦ getInt (String key, int defValue ): This method is used to retrieve an int value from the preferences. ◦ getLong (String key, long defValue ): This method is used to retrieve a long value from the preferences. ◦ getString (String key, String defValue ): This method is used to retrieve a String value from the preferences. ◦ getStringSet (String key, Set defValues ): This method is used to retrieve a set of String values from the preferences.
How to Write Data in Shared Preferences // Storing data into SharedPreferences SharedPreferences sharedPreferences =getSharedPreferences("MySharedPref“ , MODE_PRIVATE); // Creating an Editor object // to edit(write to the file) SharedPreferences.Editor myEdit = sharedPreferences.edit(); // Storing the key and its value // as the data fetched from edittext myEdit.putString ( "name", name.getText ().toString()); myEdit.putInt ( "age", Integer.parseInt ( age.getText ().toString())); // Once the changes have been made, // we need to commit to apply those changes made, // otherwise, it will throw an error myEdit.commit ();
How to Read Data in Shared Preferences // Retrieving the value using its keys // the file name must be same in both saving // and retrieving the data SharedPreferences sh = getSharedPreferences("MySharedPref" , MODE_APPEND); // The value will be default as empty string // because for the very first time // when the app is opened, // there is nothing to show String s1 = sh.getString ("name", ""); int a = sh.getInt ("age", 0); // We can then use the data name.setText (s1); age.setText ( String.valueOf (a));
THE PREFERENCE FRAMEWORK AND THE PREFERENCE ACTIVITY Android offers an XML-driven framework to create system-style Preference Screens for your applications . This has two distinct advantages: Users will be familiar with the layout and use of your settings screens. You can integrate settings screens from other applications (including system settings such as location settings) into your application’s preferences.
The preference framework consists of four parts: Preference Screen layout — An XML file that defines the hierarchy of items displayed in your Preference screens. It specifies the text and associated controls to display, the allowed values, and the Shared Preference keys to use for each control. Preference Activity and Preference Fragment — Extensions of PreferenceActivity and PreferenceFragment respectively, that are used to host the Preference Screens. Prior to Android 3.0, Preference Activities hosted the Preference Screen directly; since then, Preference Screens are hosted by Preference Fragments, which, in turn, are hosted by Preference Activities. Preference Header definition — An XML file that defines the Preference Fragments for your application and the hierarchy that should be used to display them. Shared Preference Change Listener — An implementation of the OnSharedPreferenceChangeListener class used to listen for changes to Shared Preferences.
Defining a Preference Screen Layout in XML Unlike in the standard UI layout, preference definitions are stored in the res/xml resources folder. Although conceptually they are similar to the UI layout resources Preference Screen layouts use a specialized set of controls designed specifically for preferences. Each preference layout is defined as a hierarchy, beginning with a single PreferenceScreen element: <?xml version=”1.0” encoding=”utf-8”?> < PreferenceScreen xmlns:android =”http://schemas.android.com/ apk /res/android”> </ PreferenceScreen > Additional Preference Screen elements, each of which will be represented as a selectable element that will display a new screen when clicked.
Within each Preference Screen you can include any combination of PreferenceCategory and Preference <control> elements. Preference Category elements, are used to break each Preference Screen into subcategories using a title bar separator: < PreferenceCategory android:title =”My Preference Category”/> SIM card lock, device administration, and credential storage Preference Categories used on the Security Preference Screen
Attributes of preference control android:key — The Shared Preference key against which the selected value will be recorded. android:title — The text displayed to represent the preference. android:summary — The longer text description displayed in a smaller font below the title text. android:defaultValue — The default value that will be displayed (and selected) if no preference value has been assigned to the associated preference key
Native Preference Control MultiSelectListPreference — Introduced in Android 3.0 (API level 11), this is the preference equivalent of a check box list. RingtonePreference — A specialized List Preference that presents the list of available ringtones for user selection. This is particularly useful when you’re constructing a screen to configure notification settings. You can use each preference control to construct your Preference Screen hierarchy. Alternatively, you can create your own specialized preference controls by extending the Preference classes
A simple Shared Preferences screen <?xml version="1.0" encoding="utf-8"?> < PreferenceScreen xmlns:android ="http://schemas.android.com/ apk /res/android"> < PreferenceCategory android:title ="Basics"> < Chec kBoxPreference android:key ="checkbox" android:summary ="Tap to check if on or off" android:title ="Checkbox Preference"/> < RingtonePreference android:key ="ringtone" android:showDefault ="true" android:showSilent ="true" android:summary ="Pick a ringtone you like" android:title ="Ringtone Preference" /> </ PreferenceCategory > </ PreferenceScreen >
Preference Fragment Since Android 3.0, the PreferenceFragment class has been used to host the preference screens defined by Preferences Screen resources. To create a new Preference Fragment, extend the PreferenceFragment class, as follows: public class MyPreferenceFragment extends PreferenceFragment
Preference Fragment To inflate the preferences, override the onCreate handler and call addPreferencesFromResource , as shown here: @Override public void onCreate (Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ); //Load the preferences from an XML resource addPreferencesFromResource ( R.xml.userpreferences ); } Your application can include several different Preference Fragments, which will be grouped according to the Preference Header hierarchy and displayed within a Preference Activity.
Preference Activity PreferenceActivity class is used to host the Preference Fragment hierarchy defined by a preferenceheaders resource To display settings in an activity extend the preferenceActivity class This is an extension of traditional activity class that displays a list of settings based on a hierarchy of Preference objects To create a new Preference Activity, extend the PreferenceActivity class as follows: public class MyFragmentPreferenceActivity extends PreferenceActivity
Preference Activity Inflate the Preference Screen directly in the same way as you would from a Preference Fragment — by overriding the onCreate handler and calling add PreferencesFromResource , specifying the Preference Screen layout XML resource to display within that Activity: @Override public void onCreate (Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ); addPreferencesFromResource ( R.xml.userpreferences ); }
Preference Activity Like all Activities, the Preference Activity must be included in the application manifest: Activity: <activity android:name =“ MyPreferenceActivity ” android:label =“My Preferences”> </activity> To display the application settings hosted in this Activity, open it by calling startActivity or startActivityForResult : Intent i = new Intent(this, MyPreferenceActivity.class ); startActivityForResult ( i , SHOW_PREFERENCES);