Search This Blog

Monday, 19 March 2012

Chapter 22:Preferences


Preferences






Android preferences can be set in two ways. You can create a preferences.xml file in the res/xml directory, or you can set the preferences from code.
The first example shows a preferences.xml file. Every preference needs to have a android:key value, that we call to get the preference's value. The android:title is the preference's title, and the android:summary is a summary about the preference. The android:defaultValue is the default value of the preference - fx. true or false.
Currently there are 5 different preference views:
  • The CheckBoxPreference is a simple checkbox, that can return true or false.
  • The ListPreference, which shows a radioGroup where only 1 item can be selected a time. The android:entries links to an array in the res/values/arrays, and the android:entryValues is an other array with the items to be returned.
  • The EditTextPreference shows a dialog with an editText view. This returns a String.
  • The RingtonePreference shows a radioGroup that shows the ringtones.
  • The Preference is a custom preference. This works like a Button.
  • The PreferenceScreen is a screen with preferences. When you have a PreferenceScreen inside an other PreferenceScreen, it simply opens a new screen with other preferences.
  • The PreferenceCategory is a category with preferences.
  • Custom preference

  • Edit Text Preference

  • List Preference

  • Ringtone Preference

  • Preference Screen

This is an example on the preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
        <PreferenceCategory
                android:title="First Category">
                <CheckBoxPreference
                        android:title="Checkbox Preference"
                        android:defaultValue="false"
                        android:summary="This preference can be true or false"
                        android:key="checkboxPref" />
                <ListPreference
                        android:title="List Preference"
                        android:summary="This preference allows to select an item in a array"
                        android:key="listPref"
                        android:defaultValue="digiGreen"
                        android:entries="@array/listArray"
                        android:entryValues="@array/listValues" />
        </PreferenceCategory>
        <PreferenceCategory
                android:title="Second Category">
        <EditTextPreference
                android:name="EditText Preference"
                android:summary="This allows you to enter a string"
                android:defaultValue="Nothing"
                android:title="Edit This Text"
                android:key="editTextPref" />
        <RingtonePreference
                android:name="Ringtone Preference"
                android:summary="Select a ringtone"
                android:title="Ringtones"
                android:key="ringtonePref" />
        <PreferenceScreen
                android:key="SecondPrefScreen"
                android:title="Second PreferenceScreen"
                android:summary="This is a second PreferenceScreen">
                <EditTextPreference
                        android:name="An other EditText Preference"
                        android:summary="This is a preference in the second PreferenceScreen"
                        android:title="Edit text"
                        android:key="SecondEditTextPref" />
        </PreferenceScreen>
        <Preference
                android:title="Custom Preference"
                android:summary="This works almost like a button"
                android:key="customPref" />
        </PreferenceCategory>
</PreferenceScreen>
To show the preference screen, we create a class which extends PreferenceActivity. This is an example on the preference class:

per.preferenceexample;
 
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.Toast;
 
public class Preferences extends PreferenceActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                addPreferencesFromResource(R.xml.preferences);
                // Get the custom preference
                Preference customPref = (Preference) findPreference("customPref");
                customPref
                                .setOnPreferenceClickListener(new OnPreferenceClickListener() {
 
                   public boolean onPreferenceClick(Preference preference) {
                                   Toast.makeText(getBaseContext(),
                                   "The custom preference has been clicked",
                                             Toast.LENGTH_LONG).show();
          SharedPreferences customSharedPreference = getSharedPreferences(
                  "myCustomSharedPrefs", Activity.MODE_PRIVATE);
          SharedPreferences.Editor editor = customSharedPreference
                                            .edit();
                   editor.putString("myCustomPref",
                                   "The preference has been clicked");
                                                editor.commit();
                                                return true;
                                        }
 
                                });
        }
}
We can call this activity when we click a button:

        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                Button prefBtn = (Button) findViewById(R.id.prefButton);
                prefBtn.setOnClickListener(new OnClickListener() {
 
                        public void onClick(View v) {
                                Intent settingsActivity = new Intent(getBaseContext(),
                                                Preferences.class);
                                startActivity(settingsActivity);
                        }
                });
        }

To read these preferences from code, we should create a getPrefs() method, which we can call in the onStart() method. When we call it in the onStart() method instead of onCreate(), we can be sure that the preferences load when we have set them and returned to our main activity,
The getPrefs() method could look like this:

boolean CheckboxPreference;
        String ListPreference;
        String editTextPreference;
        String ringtonePreference;
        String secondEditTextPreference;
        String customPref;
 
        private void getPrefs() {
                // Get the xml/preferences.xml preferences
                SharedPreferences prefs = PreferenceManager
                                .getDefaultSharedPreferences(getBaseContext());
                CheckboxPreference = prefs.getBoolean("checkboxPref", true);
                ListPreference = prefs.getString("listPref", "nr1");
                editTextPreference = prefs.getString("editTextPref",
                                "Nothing has been entered");
                ringtonePreference = prefs.getString("ringtonePref",
                                "DEFAULT_RINGTONE_URI");
                secondEditTextPreference = prefs.getString("SecondEditTextPref",
                                "Nothing has been entered");
                // Get the custom preference
                SharedPreferences mySharedPreferences = getSharedPreferences(
                                "myCustomSharedPrefs", Activity.MODE_PRIVATE);
                customPref = mySharedPreferences.getString("myCusomPref", "");
        }
Remember to add the following tag in your androidmanifest.xml file and add a new string item with the name "set_preferences" with the preference screen's title, for example "Preferences"

<activity
        android:name=".Preferences"
        android:label="@string/set_preferences">
</activity>

This is the final result
  • The main activity screen

  • The preference activity




preferecnce using program

When developing a mobile application, a common need that arises is the one of storing user's preferences and using them when the application starts. Since this is a recurring need, Google has created a preferences framework for us. The provided mechanism allows us to show, save and manipulate user's preferences very easily. Furthermore, the framework has support for automatic UI creation. What I mean is, that, by declaring the type of a user preference, a user interface for manipulating these preferences is automatically generated, without having to write a single line code. How does that sound for rapid application development?

In order to make use of the preferences framework, the first step is to extend the PreferenceActivity class. This is just a convenience class that derives from ListActivity and allows to bootstrap the preferences UI from an XML file. Additionally, it automatically saves to SharedPreferences behind the scenes. Don't forget that SharedPreferences is the interface responsible for accessing and modifying preference data and that we can manually manipulate it by calling the getSharedPreferences method of an Activity. In order to tie together our PreferenceActivity class and the XML layout file, we use the addPreferencesFromResource method. Thus, our onCreate method is very simple and looks like this:

1
...
2
@Override
3
public void onCreate(Bundle savedInstanceState) {    
4
    super.onCreate(savedInstanceState);       
5
    addPreferencesFromResource(R.xml.preferences);       
6
}
7
...

This assumes that we have already created a file named “preferences.xml” inside the “res/xml” folder. Then, in run-time, the activity will inflate the given XML resource and add the preference hierarchy to the current preference hierarchy. This XML file has a specific format via which we define the types of the preferences. All types derive from the Preference class, which represents the basic preference UI building block and provides the View to be displayed in the activity and the association with a SharedPreferences object to store/retrieve the preference data. Here are some of the most common subclasses that you can directly use:
  • CheckBoxPreference: Provides checkbox widget functionality. Will store a Boolean value.
  • RingtonePreference: Allows the user to choose a ringtone from those on the device. The chosen ringtone's URI will be persisted as a string.
  • EditTextPreference: Allows for string input. Will store a string into the SharedPreferences.
  • ListPreference: Displays a list of entries as a dialog. This preference will store a string into the SharedPreferences.

Also bear in mind that various preferences can be grouped into categories by using the PreferenceCategory class, which groups Preference objects and provides a disabled title above the group.

Let's examine what our XML declaration file will be consisted of. We are going to have two categories. Under the first one, we will have a CheckBoxPreference, which will enable or disable data updates to a hypothetical application and a ListPreference which through which we will define how often we want updates to happen. As you might have guessed, there is a dependency between the two preferences. This can be achieved by using the android:dependency attribute. Finally, under the second category, we will have a EditTextPreference via which a welcome message will be saved and shown when necessary. This is what the XML file looks like:


<?xml version="1.0" encoding="utf-8"?>





<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">





    <PreferenceCategory


        android:title="First Category"


        android:key="first_category">


        


        <CheckBoxPreference


            android:key="perform_updates"


            android:summary="Enable or disable data updates"


            android:title="Enable updates"


            android:defaultValue="true"


        />


        


        <ListPreference


            android:key="updates_interval"


            android:title="Updates interval"


            android:summary="Define how often updates will be performed"


            android:defaultValue="1000"


            android:entries="@array/updateInterval"


            android:entryValues="@array/updateIntervalValues"


            android:dependency="perform_updates"


        />   


            


    </PreferenceCategory>





    <PreferenceCategory


        android:title="Second Category"


        android:key="second_category">





        <EditTextPreference


            android:key="welcome_message"


            android:title="Welcome Message"


            android:summary="Define the Welcome message to be shown"


            android:dialogTitle="Welcome Message"


            android:dialogMessage="Provide a message"  


            android:defaultValue="Default welcome message" />





    </PreferenceCategory>


    


</PreferenceScreen>

Note that for the ListPreference, an android:entries attribute is defined. We use that to load predefined values which are kept in an external XML file under the name “res/values/arrays.xml”. The “updateInterval” and “updateIntervalValue” entries are used from that file. These are actually key-value pairs, so the actual value stored is the one in the second list. Here is what the file looks like:


<?xml version="1.0" encoding="utf-8"?>





<resources>





    <string-array name="updateInterval">


        <item name="1000">Every 1 second</item>


        <item name="5000">Every 5 seconds</item>


        <item name="30000">Every 30 seconds</item>


        <item name="60000">Every 1 minute</item>


        <item name="300000">Every 5 minutes</item>


    </string-array>


    


    <string-array name="updateIntervalValues">


        <item name="1000">1000</item>


        <item name="5000">5000</item>


        <item name="30000">30000</item>


        <item name="60000">60000</item>


        <item name="300000">300000</item>


    </string-array>





</resources>

As we explained, the persisting part of the equation is handled by the framework. In order to show you how to read the already persisted values, we will create another activity which will be launched from our main one. Let's first see how the main activity looks like:


package com.javacodegeeks.android.preferences;





import android.content.Intent;


import android.os.Bundle;


import android.preference.PreferenceActivity;


import android.view.Menu;


import android.view.MenuItem;





public class QuickPrefsActivity extends PreferenceActivity {


    


    @Override


    public void onCreate(Bundle savedInstanceState) {       


        super.onCreate(savedInstanceState);       


        addPreferencesFromResource(R.xml.preferences);       


    }


    


    @Override


    public boolean onCreateOptionsMenu(Menu menu) {


        menu.add(Menu.NONE, 0, 0, "Show current settings");


        return super.onCreateOptionsMenu(menu);


    }





    @Override


    public boolean onOptionsItemSelected(MenuItem item) {


        switch (item.getItemId()) {


            case 0:


                startActivity(new Intent(this, ShowSettingsActivity.class));


                return true;


        }


        return false;


    }


    


}

Nothing special here. We just provide an options menu with only one MenuItem by using the onCreateOptionsMenu method. When the user selects the specific item, we handle its actions inside the onOptionsItemSelected method and we launch a new activity using the startActivity method. If you want to learn more about option menus, check out my older tutorial named “Using options menus and customized dialogs for user interaction”. More information about starting activities can be found in my tutorial “Launching new activities with intents”.

Let's now create the “ShowSettingsActivity”. First, we have to declare it in the Android manifest file, so here what our “AndroidManifest.xml” file looks like:


<?xml version="1.0" encoding="utf-8"?>





<manifest xmlns:android="http://schemas.android.com/apk/res/android"


      package="com.javacodegeeks.android.preferences"


      android:versionCode="1"


      android:versionName="1.0">


      


    <application android:icon="@drawable/icon" android:label="@string/app_name">


        


        <activity android:name=".QuickPrefsActivity" android:label="@string/app_name">


            <intent-filter>


                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />


            </intent-filter>


        </activity>


        


        <activity android:name=".ShowSettingsActivity" />


        


    </application>


    


    <uses-sdk android:minSdkVersion="3" />





</manifest>

Here is the code for the activity itself:


package com.javacodegeeks.android.preferences;





import android.app.Activity;


import android.content.SharedPreferences;


import android.os.Bundle;


import android.preference.PreferenceManager;


import android.widget.TextView;





public class ShowSettingsActivity extends Activity {





 @Override


 protected void onCreate(Bundle savedInstanceState) {





  super.onCreate(savedInstanceState);


  setContentView(R.layout.show_settings_layout);





  SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);





  StringBuilder builder = new StringBuilder();





  builder.append("\n" + sharedPrefs.getBoolean("perform_updates", false));


  builder.append("\n" + sharedPrefs.getString("updates_interval", "-1"));


  builder.append("\n" + sharedPrefs.getString("welcome_message", "NULL"));





  TextView settingsTextView = (TextView) findViewById(R.id.settings_text_view);


  settingsTextView.setText(builder.toString());





 }





}

Inside the activity, we take reference of the SharedPreferences class by using the static method getDefaultSharedPreferences of the PreferenceManager class. Then, depending on the data type of the preference, we use the appropriate getter method, such as getBoolean or getString. Note that the second argument to those is a default value which will be used if a a value has not yet been stored. We use as keys those defined in the original “preferences.xml” file, i.e. “perform_updates”, “updates_interval” and “welcome_message”. The values are concatenated and then presented in a TextView.

Here is also the simple layout for the specific activity:


<?xml version="1.0" encoding="utf-8"?>





<LinearLayout


    xmlns:android="http://schemas.android.com/apk/res/android"


    android:orientation="vertical"


    android:layout_width="fill_parent"


    android:layout_height="fill_parent"


    >


    


    <TextView


        android:id="@+id/settings_text_view"


        android:layout_width="fill_parent"


        android:layout_height="wrap_content"


    />


    


</LinearLayout>

If we now launch the Eclipse configuration, we will get a preferences screen like the following:



Clicking on the “Updates Interval” will cause a list of options to appear:



Similarly, clicking on the “Welcome Message” preference will cause an edit text to appear:



Now let's read the already persisted values. Hit the “Menu” button on the emulator so that the options menu appears and choose the “Show current settings” item. This will launch our second activity inside which the values are read and presented as follows:






package

android.preference

Provides classes that manage application preferences and implement the preferences UI. Using these ensures that all the preferences within each application are maintained in the same manner and the user experience is consistent with that of the system and other applications.
The preferences portion of an application should be ran as a separate Activity that extends the PreferenceActivity class. In the PreferenceActivity, a PreferenceScreen object should be the root element of the layout. The PreferenceScreen contains Preference elements such as a CheckBoxPreference, EditTextPreference, ListPreference, PreferenceCategory, or RingtonePreference.
All settings made for a given Preference will be automatically saved to the application's instance of SharedPreferences. Access to the SharedPreferences is simple with getSharedPreferences().



public class

Preference

extends Object
implements Comparable<T>
java.lang.Object
   ↳
android.preference.Preference
Known Direct Subclasses
Known Indirect Subclasses

Class Overview

Represents the basic Preference UI building block displayed by a PreferenceActivity in the form of a ListView. This class provides the View to be displayed in the activity and associates with a SharedPreferences to store/retrieve the preference data.
When specifying a preference hierarchy in XML, each element can point to a subclass of Preference, similar to the view hierarchy and layouts.
This class contains a key that will be used as the key into the SharedPreferences. It is up to the subclass to decide how to store the value.



XML Attributes

android:defaultValue

The default value for the preference, which will be set either if persistence is off or persistence is on and the preference is not found in the persistent storage.
May be a reference to another resource, in the form "@[+][package:]type:name" or to a theme attribute in the form "?[package:][type:]name".
May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
May be an integer value, such as "100".
May be a boolean value, either "true" or "false".
May be a floating point value, such as "1.2".
This corresponds to the global attribute resource symbol defaultValue.
Related Methods

android:dependency

The key of another Preference that this Preference will depend on. If the other Preference is not set or is off, this Preference will be disabled.
Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol dependency.
Related Methods

android:enabled

Whether the Preference is enabled.
Must be a boolean value, either "true" or "false".
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol enabled.
Related Methods

android:fragment

When used inside of a modern PreferenceActivity, this declares a new PreferenceFragment to be shown when the user selects this item.
Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol fragment.
Related Methods

android:icon

The optional icon for the preference
Must be a reference to another resource, in the form "@[+][package:]type:name" or to a theme attribute in the form "?[package:][type:]name".
This corresponds to the global attribute resource symbol icon.
Related Methods

android:key

The key to store the Preference value.
Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol key.
Related Methods

android:layout

The layout for the Preference in a PreferenceActivity screen. This should rarely need to be changed, look at widgetLayout instead.
Must be a reference to another resource, in the form "@[+][package:]type:name" or to a theme attribute in the form "?[package:][type:]name".
This corresponds to the global attribute resource symbol layout.
Related Methods

android:order

The order for the Preference (lower values are to be ordered first). If this is not specified, the default orderin will be alphabetic.
Must be an integer value, such as "100".
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol order.
Related Methods

android:persistent

Whether the Preference stores its value to the shared preferences.
Must be a boolean value, either "true" or "false".
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol persistent.
Related Methods

android:selectable

Whether the Preference is selectable.
Must be a boolean value, either "true" or "false".
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol selectable.
Related Methods

android:shouldDisableView

Whether the view of this Preference should be disabled when this Preference is disabled.
Must be a boolean value, either "true" or "false".
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol shouldDisableView.
Related Methods

android:summary

The summary for the Preference in a PreferenceActivity screen.
Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol summary.
Related Methods

android:title

The title for the Preference in a PreferenceActivity screen.
Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol title.
Related Methods

android:widgetLayout

The layout for the controllable widget portion of a Preference. This is inflated into the layout for a Preference and should be used more frequently than the layout attribute. For example, a checkbox preference would specify a custom layout (consisting of just the CheckBox) here.
Must be a reference to another resource, in the form "@[+][package:]type:name" or to a theme attribute in the form "?[package:][type:]name".
This corresponds to the global attribute resource symbol widgetLayout.
Related Methods

Constants

public static final int DEFAULT_ORDER

Since: API Level 1
Specify for setOrder(int) if a specific order is not required.
Constant Value: 2147483647 (0x7fffffff)

Public Constructors

public Preference (Context context, AttributeSet attrs, int defStyle)

Since: API Level 1
Perform inflation from XML and apply a class-specific base style. This constructor of Preference allows subclasses to use their own base style when they are inflating. For example, a CheckBoxPreference constructor calls this version of the super class constructor and supplies android.R.attr.checkBoxPreferenceStyle for defStyle. This allows the theme's checkbox preference style to modify all of the base preference attributes as well as the CheckBoxPreference class's attributes.
Parameters
context
The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc.
attrs
The attributes of the XML tag that is inflating the preference.
defStyle
The default style to apply to this preference. If 0, no style will be applied (beyond what is included in the theme). This may either be an attribute resource, whose value will be retrieved from the current theme, or an explicit style resource.
See Also

public Preference (Context context, AttributeSet attrs)

Since: API Level 1
Constructor that is called when inflating a Preference from XML. This is called when a Preference is being constructed from an XML file, supplying attributes that were specified in the XML file. This version uses a default style of 0, so the only attribute values applied are those in the Context's Theme and the given AttributeSet.
Parameters
context
The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc.
attrs
The attributes of the XML tag that is inflating the preference.
See Also

public Preference (Context context)

Since: API Level 1
Constructor to create a Preference.
Parameters
context
The Context in which to store Preference values.

Public Methods

public int compareTo (Preference another)

Since: API Level 1
Compares Preference objects based on order (if set), otherwise alphabetically on the titles.
Parameters
another
The Preference to compare to this one.
Returns
  • 0 if the same; less than 0 if this Preference sorts ahead of another; greater than 0 if this Preference sorts after another.

public Context getContext ()

Since: API Level 1
Returns the Context of this Preference. Each Preference in a Preference hierarchy can be from different Context (for example, if multiple activities provide preferences into a single PreferenceActivity). This Context will be used to save the Preference values.
Returns
  • The Context of this Preference.

public String getDependency ()

Since: API Level 1
Returns the key of the dependency on this Preference.
Returns
  • The key of the dependency.
See Also

public SharedPreferences.Editor getEditor ()

Since: API Level 1
Returns an SharedPreferences.Editor where this Preference can save its value(s). Usually it's easier to use one of the helper save methods: persistBoolean(boolean), persistFloat(float), persistInt(int), persistLong(long), persistString(String). To read values, see getSharedPreferences(). If shouldCommit() returns true, it is this Preference's responsibility to commit.
In some cases, writes to this will not be committed right away and hence not show up in the SharedPreferences, this is intended behavior to improve performance.
Returns
  • A SharedPreferences.Editor where this preference saves its value(s), or null if it isn't attached to a Preference hierarchy.
See Also

public Bundle getExtras ()

Since: API Level 11
Return the extras Bundle object associated with this preference, creating a new Bundle if there currently isn't one. You can use this to get and set individual extra key/value pairs.

public String getFragment ()

Since: API Level 11
Return the fragment class name associated with this Preference.
Returns

public Drawable getIcon ()

Since: API Level 11
Returns the icon of this Preference.
Returns
  • The icon.
See Also

public Intent getIntent ()

Since: API Level 1
Return the Intent associated with this Preference.
Returns

public String getKey ()

Since: API Level 1
Gets the key for this Preference, which is also the key used for storing values into SharedPreferences.
Returns
  • The key.

public int getLayoutResource ()

Since: API Level 1
Gets the layout resource that will be shown as the View for this Preference.
Returns
  • The layout resource ID.

public Preference.OnPreferenceChangeListener getOnPreferenceChangeListener ()

Since: API Level 1
Returns the callback to be invoked when this Preference is changed by the user (but before the internal state has been updated).
Returns
  • The callback to be invoked.

public Preference.OnPreferenceClickListener getOnPreferenceClickListener ()

Since: API Level 1
Returns the callback to be invoked when this Preference is clicked.
Returns
  • The callback to be invoked.

public int getOrder ()

Since: API Level 1
Gets the order of this Preference with respect to other Preference objects on the same level.
Returns
  • The order of this Preference.
See Also

public PreferenceManager getPreferenceManager ()

Since: API Level 1
Gets the PreferenceManager that manages this Preference object's tree.
Returns

public SharedPreferences getSharedPreferences ()

Since: API Level 1
Returns the SharedPreferences where this Preference can read its value(s). Usually, it's easier to use one of the helper read methods: getPersistedBoolean(boolean), getPersistedFloat(float), getPersistedInt(int), getPersistedLong(long), getPersistedString(String). To save values, see getEditor().
In some cases, writes to the getEditor() will not be committed right away and hence not show up in the returned SharedPreferences, this is intended behavior to improve performance.
Returns
  • The SharedPreferences where this Preference reads its value(s), or null if it isn't attached to a Preference hierarchy.
See Also

public boolean getShouldDisableView ()

Since: API Level 1
Checks whether this Preference should disable its view when it's action is disabled.
Returns
  • True if it should disable the view.
See Also

public CharSequence getSummary ()

Since: API Level 1
Returns the summary of this Preference.
Returns
  • The summary.
See Also

public CharSequence getTitle ()

Since: API Level 1
Returns the title of this Preference.
Returns
  • The title.
See Also

public int getTitleRes ()

Since: API Level 14
Returns the title resource ID of this Preference. If the title did not come from a resource, 0 is returned.
Returns
  • The title resource.
See Also

public View getView (View convertView, ViewGroup parent)

Since: API Level 1
Gets the View that will be shown in the PreferenceActivity.
Parameters
convertView
The old View to reuse, if possible. Note: You should check that this View is non-null and of an appropriate type before using. If it is not possible to convert this View to display the correct data, this method can create a new View.
parent
The parent that this View will eventually be attached to.
Returns
  • Returns the same Preference object, for chaining multiple calls into a single statement.
See Also

public int getWidgetLayoutResource ()

Since: API Level 1
Gets the layout resource for the controllable widget portion of this Preference.
Returns
  • The layout resource ID.

public boolean hasKey ()

Since: API Level 1
Checks whether this Preference has a valid key.
Returns
  • True if the key exists and is not a blank string, false otherwise.

public boolean isEnabled ()

Since: API Level 1
Checks whether this Preference should be enabled in the list.
Returns
  • True if this Preference is enabled, false otherwise.

public boolean isPersistent ()

Since: API Level 1
Checks whether this Preference is persistent. If it is, it stores its value(s) into the persistent SharedPreferences storage.
Returns
  • True if it is persistent.

public boolean isSelectable ()

Since: API Level 1
Checks whether this Preference should be selectable in the list.
Returns
  • True if it is selectable, false otherwise.

public void notifyDependencyChange (boolean disableDependents)

Since: API Level 1
Notifies any listening dependents of a change that affects the dependency.
Parameters
disableDependents
Whether this Preference should disable its dependents.

public void onDependencyChanged (Preference dependency, boolean disableDependent)

Since: API Level 1
Called when the dependency changes.
Parameters
dependency
The Preference that this Preference depends on.
disableDependent
Set true to disable this Preference.

public Bundle peekExtras ()

Since: API Level 11
Return the extras Bundle object associated with this preference, returning null if there is not currently one.

public void restoreHierarchyState (Bundle container)

Since: API Level 1
Restore this Preference hierarchy's previously saved state from the given container.
Parameters
container
The Bundle that holds the previously saved state.
See Also

public void saveHierarchyState (Bundle container)

Since: API Level 1
Store this Preference hierarchy's frozen state into the given container.
Parameters
container
The Bundle in which to save the instance of this Preference.
See Also

public void setDefaultValue (Object defaultValue)

Since: API Level 1
Sets the default value for this Preference, which will be set either if persistence is off or persistence is on and the preference is not found in the persistent storage.
Parameters
defaultValue
The default value.

public void setDependency (String dependencyKey)

Since: API Level 1
Sets the key of a Preference that this Preference will depend on. If that Preference is not set or is off, this Preference will be disabled.
Parameters
dependencyKey
The key of the Preference that this depends on.

public void setEnabled (boolean enabled)

Since: API Level 1
Sets whether this Preference is enabled. If disabled, it will not handle clicks.
Parameters
enabled
Set true to enable it.

public void setFragment (String fragment)

Since: API Level 11
Sets the class name of a fragment to be shown when this Preference is clicked.
Parameters
fragment
The class name of the fragment associated with this Preference.

public void setIcon (Drawable icon)

Since: API Level 11
Sets the icon for this Preference with a Drawable. This icon will be placed into the ID icon within the View created by onCreateView(ViewGroup).
Parameters
icon
The optional icon for this Preference.

public void setIcon (int iconResId)

Since: API Level 11
Sets the icon for this Preference with a resource ID.
Parameters
iconResId
The icon as a resource ID.
See Also

public void setIntent (Intent intent)

Since: API Level 1
Sets an Intent to be used for startActivity(Intent) when this Preference is clicked.
Parameters
intent
The intent associated with this Preference.

public void setKey (String key)

Since: API Level 1
Sets the key for this Preference, which is used as a key to the SharedPreferences. This should be unique for the package.
Parameters
key
The key for the preference.

public void setLayoutResource (int layoutResId)

Since: API Level 1
Sets the layout resource that is inflated as the View to be shown for this Preference. In most cases, the default layout is sufficient for custom Preference objects and only the widget layout needs to be changed.
This layout should contain a ViewGroup with ID widget_frame to be the parent of the specific widget for this Preference. It should similarly contain title and summary.
Parameters
layoutResId
The layout resource ID to be inflated and returned as a View.
See Also

public void setOnPreferenceChangeListener (Preference.OnPreferenceChangeListener onPreferenceChangeListener)

Since: API Level 1
Sets the callback to be invoked when this Preference is changed by the user (but before the internal state has been updated).
Parameters
onPreferenceChangeListener
The callback to be invoked.

public void setOnPreferenceClickListener (Preference.OnPreferenceClickListener onPreferenceClickListener)

Since: API Level 1
Sets the callback to be invoked when this Preference is clicked.
Parameters
onPreferenceClickListener
The callback to be invoked.

public void setOrder (int order)

Since: API Level 1
Sets the order of this Preference with respect to other Preference objects on the same level. If this is not specified, the default behavior is to sort alphabetically. The setOrderingAsAdded(boolean) can be used to order Preference objects based on the order they appear in the XML.
Parameters
order
The order for this Preference. A lower value will be shown first. Use DEFAULT_ORDER to sort alphabetically or allow ordering from XML.
See Also

public void setPersistent (boolean persistent)

Since: API Level 1
Sets whether this Preference is persistent. When persistent, it stores its value(s) into the persistent SharedPreferences storage.
Parameters
persistent
Set true if it should store its value(s) into the SharedPreferences.

public void setSelectable (boolean selectable)

Since: API Level 1
Sets whether this Preference is selectable.
Parameters
selectable
Set true to make it selectable.

public void setShouldDisableView (boolean shouldDisableView)

Since: API Level 1
Sets whether this Preference should disable its view when it gets disabled.
For example, set this and setEnabled(boolean) to false for preferences that are only displaying information and 1) should not be clickable 2) should not have the view set to the disabled state.
Parameters
shouldDisableView
Set true if this preference should disable its view when the preference is disabled.

public void setSummary (int summaryResId)

Since: API Level 1
Sets the summary for this Preference with a resource ID.
Parameters
summaryResId
The summary as a resource.
See Also

public void setSummary (CharSequence summary)

Since: API Level 1
Sets the summary for this Preference with a CharSequence.
Parameters
summary
The summary for the preference.

public void setTitle (int titleResId)

Since: API Level 1
Sets the title for this Preference with a resource ID.
Parameters
titleResId
The title as a resource ID.
See Also

public void setTitle (CharSequence title)

Since: API Level 1
Sets the title for this Preference with a CharSequence. This title will be placed into the ID title within the View created by onCreateView(ViewGroup).
Parameters
title
The title for this Preference.

public void setWidgetLayoutResource (int widgetLayoutResId)

Since: API Level 1
Sets The layout for the controllable widget portion of this Preference. This is inflated into the main layout. For example, a CheckBoxPreference would specify a custom layout (consisting of just the CheckBox) here, instead of creating its own main layout.
Parameters
widgetLayoutResId
The layout resource ID to be inflated into the main layout.
See Also

public boolean shouldCommit ()

Since: API Level 1
Returns whether the Preference should commit its saved value(s) in getEditor(). This may return false in situations where batch committing is being done (by the manager) to improve performance.
Returns
  • Whether the Preference should commit its saved value(s).
See Also

public boolean shouldDisableDependents ()

Since: API Level 1
Checks whether this preference's dependents should currently be disabled.
Returns
  • True if the dependents should be disabled, otherwise false.

public String toString ()

Since: API Level 1
Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:
   getClass().getName() + '@' + Integer.toHexString(hashCode())
See Writing a useful toString method if you intend implementing your own toString method.
Returns
  • a printable representation of this object.

Protected Methods

protected boolean callChangeListener (Object newValue)

Since: API Level 1
Call this method after the user changes the preference, but before the internal state is set. This allows the client to ignore the user value.
Parameters
newValue
The new value of this Preference.
Returns
  • True if the user value should be set as the preference value (and persisted).

protected Preference findPreferenceInHierarchy (String key)

Since: API Level 1
Finds a Preference in this hierarchy (the whole thing, even above/below your PreferenceScreen screen break) with the given key.
This only functions after we have been attached to a hierarchy.
Parameters
key
The key of the Preference to find.
Returns
  • The Preference that uses the given key.

protected boolean getPersistedBoolean (boolean defaultReturnValue)

Since: API Level 1
Attempts to get a persisted boolean from the SharedPreferences.
Parameters
defaultReturnValue
The default value to return if either this Preference is not persistent or this Preference is not in the SharedPreferences.
Returns
  • The value from the SharedPreferences or the default return value.
See Also

protected float getPersistedFloat (float defaultReturnValue)

Since: API Level 1
Attempts to get a persisted float from the SharedPreferences.
Parameters
defaultReturnValue
The default value to return if either this Preference is not persistent or this Preference is not in the SharedPreferences.
Returns
  • The value from the SharedPreferences or the default return value.
See Also

protected int getPersistedInt (int defaultReturnValue)

Since: API Level 1
Attempts to get a persisted int from the SharedPreferences.
Parameters
defaultReturnValue
The default value to return if either this Preference is not persistent or this Preference is not in the SharedPreferences.
Returns
  • The value from the SharedPreferences or the default return value.
See Also

protected long getPersistedLong (long defaultReturnValue)

Since: API Level 1
Attempts to get a persisted long from the SharedPreferences.
Parameters
defaultReturnValue
The default value to return if either this Preference is not persistent or this Preference is not in the SharedPreferences.
Returns
  • The value from the SharedPreferences or the default return value.
See Also

protected String getPersistedString (String defaultReturnValue)

Since: API Level 1
Attempts to get a persisted String from the SharedPreferences.
This will check if this Preference is persistent, get the SharedPreferences from the PreferenceManager, and get the value.
Parameters
defaultReturnValue
The default value to return if either the Preference is not persistent or the Preference is not in the shared preferences.
Returns
  • The value from the SharedPreferences or the default return value.
See Also

protected void notifyChanged ()

Since: API Level 1
Should be called when the data of this Preference has changed.

protected void notifyHierarchyChanged ()

Since: API Level 1
Should be called when a Preference has been added/removed from this group, or the ordering should be re-evaluated.

protected void onAttachedToActivity ()

Since: API Level 1
Called when the Preference hierarchy has been attached to the PreferenceActivity. This can also be called when this Preference has been attached to a group that was already attached to the PreferenceActivity.

protected void onAttachedToHierarchy (PreferenceManager preferenceManager)

Since: API Level 1
Called when this Preference has been attached to a Preference hierarchy. Make sure to call the super implementation.
Parameters
preferenceManager
The PreferenceManager of the hierarchy.

protected void onBindView (View view)

Since: API Level 1
Binds the created View to the data for this Preference.
This is a good place to grab references to custom Views in the layout and set properties on them.
Make sure to call through to the superclass's implementation.
Parameters
view
The View that shows this Preference.
See Also

protected void onClick ()

Since: API Level 1
Processes a click on the preference. This includes saving the value to the SharedPreferences. However, the overridden method should call callChangeListener(Object) to make sure the client wants to update the preference's state with the new value.

protected View onCreateView (ViewGroup parent)

Since: API Level 1
Creates the View to be shown for this Preference in the PreferenceActivity. The default behavior is to inflate the main layout of this Preference (see setLayoutResource(int). If changing this behavior, please specify a ViewGroup with ID widget_frame.
Make sure to call through to the superclass's implementation.
Parameters
parent
The parent that this View will eventually be attached to.
Returns
  • The View that displays this Preference.
See Also

protected Object onGetDefaultValue (TypedArray a, int index)

Since: API Level 1
Called when a Preference is being inflated and the default value attribute needs to be read. Since different Preference types have different value types, the subclass should get and return the default value which will be its value type.
For example, if the value type is String, the body of the method would proxy to getString(int).
Parameters
a
The set of attributes.
index
The index of the default value attribute.
Returns
  • The default value of this preference type.

protected void onPrepareForRemoval ()

Since: API Level 1
Called when this Preference is being removed from the hierarchy. You should remove any references to this Preference that you know about. Make sure to call through to the superclass implementation.

protected void onRestoreInstanceState (Parcelable state)

Since: API Level 1
Hook allowing a Preference to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState(). This function will never be called with a null state.
Parameters
state
The saved state that had previously been returned by onSaveInstanceState().
See Also

protected Parcelable onSaveInstanceState ()

Since: API Level 1
Hook allowing a Preference to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can be reconstructed later.
Returns
  • A Parcelable object containing the current dynamic state of this Preference, or null if there is nothing interesting to save. The default implementation returns null.
See Also

protected void onSetInitialValue (boolean restorePersistedValue, Object defaultValue)

Since: API Level 1
Implement this to set the initial value of the Preference.
If restorePersistedValue is true, you should restore the Preference value from the SharedPreferences. If restorePersistedValue is false, you should set the Preference value to defaultValue that is given (and possibly store to SharedPreferences if shouldPersist() is true).
This may not always be called. One example is if it should not persist but there is no default value given.
Parameters
restorePersistedValue
True to restore the persisted value; false to use the given defaultValue.
defaultValue
The default value for this Preference. Only use this if restorePersistedValue is false.

protected boolean persistBoolean (boolean value)

Since: API Level 1
Attempts to persist a boolean to the SharedPreferences.
Parameters
value
The value to persist.
Returns
  • True if this Preference is persistent. (This is not whether the value was persisted, since we may not necessarily commit if there will be a batch commit later.)
See Also

protected boolean persistFloat (float value)

Since: API Level 1
Attempts to persist a float to the SharedPreferences.
Parameters
value
The value to persist.
Returns
  • True if this Preference is persistent. (This is not whether the value was persisted, since we may not necessarily commit if there will be a batch commit later.)
See Also

protected boolean persistInt (int value)

Since: API Level 1
Attempts to persist an int to the SharedPreferences.
Parameters
value
The value to persist.
Returns
  • True if the Preference is persistent. (This is not whether the value was persisted, since we may not necessarily commit if there will be a batch commit later.)
See Also

protected boolean persistLong (long value)

Since: API Level 1
Attempts to persist a long to the SharedPreferences.
Parameters
value
The value to persist.
Returns
  • True if this Preference is persistent. (This is not whether the value was persisted, since we may not necessarily commit if there will be a batch commit later.)
See Also

protected boolean persistString (String value)

Since: API Level 1
Attempts to persist a String to the SharedPreferences.
This will check if this Preference is persistent, get an editor from the PreferenceManager, put in the string, and check if we should commit (and commit if so).
Parameters
value
The value to persist.
Returns
  • True if the Preference is persistent. (This is not whether the value was persisted, since we may not necessarily commit if there will be a batch commit later.)
See Also

protected boolean shouldPersist ()

Since: API Level 1
Checks whether, at the given time this method is called, this Preference should store/restore its value(s) into the SharedPreferences. This, at minimum, checks whether this Preference is persistent and it currently has a key. Before you save/restore from the SharedPreferences, check this first.
Returns
  • True if it should persist the value.



SharedPreference



What are SharedPreferences?
With this interface you can modify all that preferences that you want to store on phone.
For example you want to save if a user wants a feature activated or not, and a good
and simply way is characterized by SharedPreferences.
When you use your own sharedPreferences you have to use a String identifier for the preferencesName
and a mode to access them (for example Context.MODE_PRIVATE).
To read data from preferences you can read directly from preferences, pref.read(String identifier, default) ,
but to modify data you have to obtain an editor, apply the modifies and the commit them.


Some examples:
//------get sharedPreferences
SharedPreferences pref = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
//-------get a value from them
pref.getString("NAME", "Android");
//--------modify the value
pref.edit().putString("NAME", "Simone").commit();
//--------reset preferences
pref.edit().clear().commit();

Discussion about posted project:
As you can see in the image at the beginning of this tutorial I have written a simply but articulated
activity to store and get some data about a person in a SharedPreferences.
String: Name, Surname
Integer: Age
In the code, that you can download from the link below, you will find:
- main.xml to manage the layout (3 edittext and 2 buttons to save and reset preferences)
- PreferenceConnector a class that simplify the interaction with SharedPreferences
- PreferencesActivity: the activity that is the engine for out simply app
With these three elements we recive inputs from user and we use SharedPreferences, related to our app
to store the recived data. In fact if you compile the three edittext and push save, when you enter a second
time in the app you will find the elements stored in the SharedPreferences (Reset to delete them all)










































No comments:

Post a Comment