We saw before that we can persist an application’s data using SQLite database. Android offers another way to store user’s data through using preferences.
Android preferences is a key/value entries that store data that can be specific to a certain activity or shared among all activities within the application.
the data are stored in a xml file within the application folders.
Saving Preferences
We can save preferences in three ways:
- Preferences can be retrieved only by a single activity.
- Preferences can be shared and retrieved among all activities within the application.
- Preferences can be shared and retrieved through all applications on the device.
Saving Activity-level preferences:
To save preferences that are accessed only from a single activity, we do it like this:
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor=prefs.edit(); editor.putString("pref 1", "some text"); editor.commit();
We get a SharedPreferences object by calling getPreferences(int mode) method which takes an integer value as a parameter, the mode value can be one of the following:
- Context.MODE_PRIVATE (0): a file creating mode that makes the created file only accessible by applications with the same user ID (access the file from the same application context, will desctribe later).
- Context.MODE_WORLD_READABLE (1): file mode makes the file readable from other applications.
- Context.MODE_WORLD_WRITEABLE (2): file mode allows other applications to write to the file.
Then we get an instance of SharedPreferences.Editor and write the preference value with editor.putString(String key, String value) method.
shared preferences allows you to insert preferences using the following methods:
- editor.putBoolean(String key, boolean value).
- editor.putFloat(String key,float value).
- editor.putInt(String key, int value).
- editor.putLong(String key, long value)
- editor.putString(String key, String value)
Then we call edit.commit() to save the preferences to the file. commit returns a boolean indicating the result of saving, true if successful and false if failed.
Reading preferences values:
To read preferences values:
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE); String val=prefs.getString("pref 1", "some text");
We use sharedpreferences.getString(String key, String defaultValue) (or get boolean/float/int) to return the value stored with a specific key or defaultValue if not found.
Saving Application-level preferences:
To save preferences that can be retrieved from all activities in the application we do it like this:
SharedPreferences prefs= getSharedPreferences("demopref", Context.MODE_WORLD_READABLE); SharedPreferences.Editor editor=prefs.edit(); editor.putString("demostring", "hello"); editor.commit();
Same as the code above, but the difference is that we give our preferences file a name (demopref in this case) so that other activities can reference that preferences file.
Sharing preferences across applications:
We can store preferences in one application and read them in another application, this is done reading the preferences file by loading them through the first application’s context.
Let’s assume we have two applications:
- Application 1 with package name “com.mina.prefdemo”.
- Application2 with package name “com.mina.demoapp”.
If application1 creates a preferences file with the name “demopref” and inserts a String preference with the key/value “demostring/hello”.
now we access this file and value from application 2 like this:
Context con; try { con = createPackageContext("com.minasamy.prefdemo", 0); SharedPreferences pref=con.getSharedPreferences("demopref", Context.MODE_PRIVATE); String x=pref.getString("demostring", "not found"); txt.setText(x); } catch (NameNotFoundException e) { Log.e(Tag, e.toString()); }
Creating Preferences Activities:
Android provides another nice way of presenting and saving preferences. you can create Activities that extend PreferenceActivity.
PreferenceActivity is an activity that displays a set of built-in preferences related widgets that are defined in xml file.
The preference activity can be divided to several PreferenceCategory each containing a set of related preferences.
The preferences widgets that Android provide are:
- CheckBoxPreference: displays a check box widget.
- EditTextPreference: displays an EditText widget to save user prefs.
- RingtonePreference: displays a list with the ringtones on the device.
- ListPreference: displays a list of key/value items.
Each one of these preferences widgets is associated with a preference key. it’s value is persisted instantly as the widget selection changes.
we can construct our preferences screen xml (saved in res/xml directory) layout like this:
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="Catogory one" android:summary="sample summary"> <CheckBoxPreference android:title="Enable" android:key="pref_enable" android:summary="enables a preference"/> <EditTextPreference android:summary="Edit text prefrence" android:title="Edit" android:key="pref_edit"/> </PreferenceCategory> <PreferenceCategory android:title="Category2" android:summary="sample summary"> <RingtonePreference android:key="pref_ring" android:title="Ringtones preference"/> <ListPreference android:key="pref_list" android:title="List Preference" android:dialogTitle="List Pref Dialog" android:entries="@array/pref_items" android:entryValues="@array/pref_items_values"/> </PreferenceCategory>
Then from our activity:
public class PrefActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.prefs); } }
The activity will look like this:
The ListPreference can be associated with String array resources as it’s key/value entries
<string-array name="pref_items"> <item>Item1</item> <item>Item2</item> <item>Item3</item> <item>Item4</item> <item>Item5</item> </string-array> <string-array name="pref_items_values"> <item>1</item> <item>2</item> <item>3</item> <item>4</item> <item>5</item> </string-array>
To reference the preference widgets programmatically:
EditTextPreference pref_edit=(EditTextPreference)findPreference("pref_edit");
And that’s was all about Android preferences. stay tuned for another tutorial next week