0% found this document useful (0 votes)
4 views23 pages

Preference

The document explains how to create, save, and retrieve data using Shared Preferences in Android, which allows storing small amounts of primitive data as key/value pairs. It details the methods for writing and reading data, as well as the framework for creating preference screens using XML. Additionally, it covers the use of PreferenceActivity and PreferenceFragment to manage and display preferences in a user-friendly manner.

Uploaded by

jyothi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views23 pages

Preference

The document explains how to create, save, and retrieve data using Shared Preferences in Android, which allows storing small amounts of primitive data as key/value pairs. It details the methods for writing and reading data, as well as the framework for creating preference screens using XML. Additionally, it covers the use of PreferenceActivity and PreferenceFragment to manage and display preferences in a user-friendly manner.

Uploaded by

jyothi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Creating ,Saving And Retrieving

Shared Preference
▪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.
▪For example, you might have a key being “username” and for the
value, you might store the user’s username. And then you could
retrieve that by its key (here username)
▪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);
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.
By using this framework you can create Preference Activities that are
consistent with those used in both native and other third-party 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
CheckBoxPreference — A standard preference check box control
used to set preferences to true or false.
EditTextPreference — Allows users to enter a string value as a
preference. Selecting the preference text at run time will display a
text-entry dialog.
ListPreference — The preference equivalent of a spinner. Selecting
this preference will display a dialog box containing a list of values
from which to select. You can specify different arrays to contain the
display text and selection values.
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">
<CheckBoxPreference
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); }
Like all Activities, the Preference Activity must be included in the application
manifest:
<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);

You might also like