Download presentation
1
Data Storage: Part 1 (Preferences)
2
Data Storage in Android
Shared Preferences lightweight data storage mechanism primarily for saving application settings and user information Standard Java File I/O (plus Android helper methods) save files directly on the device can use both internal and external storage SQLite Database store structured application data in a private database full relational database capability Content Provider make private data available to other applications exposes read/write access to application data ©SoftMoore Consulting
3
Shared Preferences The SharedPreferences interface (in package android.content) provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types and strings. similar to saving data in a Bundle Can be used to save the following data types boolean – float int – long String − Set<String> Shared preference data will persist across user sessions even if the application is killed. ©SoftMoore Consulting
4
Overview of Shared Preferences
Examples of data stored in shared preferences: user name – password address – high score An application can have multiple sets of application preferences, where each set has a name. Preferences can be stored at the activity level or the application level. In general, they are not shared outside the application. Application preferences are stored in XML files in the Android file system as follows: /data/data/<package name>/shared_prefs/<pref filename>.xml ©SoftMoore Consulting
5
Obtaining a SharedPreferences Object
Two methods that return a SharedPreferences object: getSharedPreferences(String name, int mode) Use if you need multiple preferences files identified by name. Name is specified as the first parameter. If a preferences file by this name does not exist, it will be created when you retrieve an editor. Preferences can be accessed by all activities in the application. getPreferences(int mode) Use if you need only one preferences file for your Activity. Only one preferences file for an Activity – don't supply a name. Calls method getSharedPreferences(String, int) passing in this activity’s class name as the preferences name. Preferences are not shared with other activities in the application. ©SoftMoore Consulting
6
Shared Preference Modes
MODE_PRIVATE created file can be accessed only by the calling application generally the only preference mode that you should use MODE_WORLD_READABLE (deprecated in API level 17) other applications have read access to the created file MODE_WORLD_WRITEABLE (deprecated in API level 17) other applications have write access to the created file MODE_MULTI_PROCESS used if multiple processes are mutating the same SharedPreferences file always on in apps targeting Gingerbread (Android 2.3) and below, and off by default in later versions ©SoftMoore Consulting
7
Writing/Reading Shared Preferences
To write shared preference values: Call edit() to get a SharedPreferences.Editor. Add values with editor “put” methods such as putBoolean() and putString(). Commit the new values with apply() or commit(). To read shared preference values: Use SharedPreferences “get” methods such as getBoolean() and getString(). The “get” methods have two parameters the preference key string a default value to return if the preference is undefined ©SoftMoore Consulting
8
Selected Methods for Retrieving Shared Preferences
// in interface SharedPreferences boolean getBoolean(String key, boolean defValue) float getFloat(String key, float defValue) int getInt(String key, int defValue) long getLong(String key, long defValue) String getString(String key, String defValue) Set<String> getStringSet(String key, Set<String> defValues) ©SoftMoore Consulting
9
Selected Methods for Saving Shared Preferences
// in interface SharedPreferences.Editor void apply() boolean commit() SharedPreferences.Editor putBoolean(String key, boolean value) SharedPreferences.Editor putFloat(String key, float value) SharedPreferences.Editor putInt(String key, int value) SharedPreferences.Editor putLong(String key, long value) SharedPreferences.Editor putString(String key, String value) SharedPreferences.Editor putStringSet(String key, Set<String> values) SharedPreferences.Editor remove(String key) ©SoftMoore Consulting
10
Differences Between Methods apply() and commit()
Returns a boolean value to indicate if the new values were successfully written to persistent storage. Writes its preferences out to persistent storage synchronously (can block the UI thread) apply() Commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk. does not block the UI thread, but you won’t be notified of any failures. Use apply() if you don't care about the return value and you’re using this from your application’s UI thread. ©SoftMoore Consulting
11
Example: Shared Preferences
public static final String PREFS_NAME = "MyPrefsFile"; Create shared preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", silentMode); // Commit the edits! editor.apply(); Retrieve shared preferences getSharedPreferences(PREFS_NAME, MODE_PRIVATE); boolean silentMode = settings.getBoolean("silentMode", false); a boolean variable ©SoftMoore Consulting
12
SharedPreferences APIs Versus the Preference APIs
The SharedPreferences APIs discussed in the previous slides are only for reading and writing key-value pairs and should not be confused with the Preference APIs As discussed in the remaining slides, the Preference APIs are for building a user interface for application settings that is consistent with the user experience in other Android applications, including system settings. Note that the Preference APIs use SharedPreferences as their implementation to save the application settings. ©SoftMoore Consulting
13
The Preferences Framework
Android provides a standardized framework for setting preferences using preference categories and screens defined in an XML file. The Android system generates a user screen to manipulate the preferences defined in the XML file. The preferences are stored in shared preferences and can be retrieved by calling the getPreferences() method. ©SoftMoore Consulting
14
Example: Preferences XML File (res/xml/settings.xml)
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android=" <PreferenceCategory android:title="First Category"> <CheckBoxPreference android:title="Checkbox Preference" android:defaultValue="false" android:summary="This preference can be true or ..." android:key="checkboxPref" /> <ListPreference android:title="List Preference" android:summary="This preference allows you to ..." android:key="listPref" android:defaultValue="digiGreen" /> </PreferenceCategory> ©SoftMoore Consulting
15
Example: Preferences XML File (continued)
<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"> ©SoftMoore Consulting
16
Example: Preferences XML File (continued)
<EditTextPreference android:name="An other EditText Preference" android:summary="This is a preference in ..." android:title="Edit text" android:key="SecondEditTextPref" /> </PreferenceScreen> </PreferenceCategory> ©SoftMoore Consulting
17
Displaying Preferences in an Activity
Prior to Android 3.0 (Honeycomb, API level 11) create a class that extends PreferenceActivity call addPreferencesFromResource(R.xml.<filename>) For Android 3.0 (Honeycomb, API level 11) and higher create a class that extends PreferenceFragment add the fragment to an Activity just as you would for any other Fragment. ©SoftMoore Consulting
18
Example 1: Displaying Preferences in an Activity (Prior to Android 3
import android.os.Bundle; import android.preference.PreferenceActivity; public class Preferences extends PreferenceActivity protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.preferences); } This method is now deprecated. ©SoftMoore Consulting
19
Example 2: Displaying Preferences in an Activity (Android 3
Example 2: Displaying Preferences in an Activity (Android 3.0 and Higher) import android.os.Bundle; import android.preference.PreferenceFragment; public class SettingsFragment extends PreferenceFragment public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.settings); } ©SoftMoore Consulting
20
Example 2: Displaying Preferences in an Activity (continued)
import android.app.Activity; import android.os.Bundle; public class Settings extends Activity public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); // Display the fragment as the main content. getFragmentManager() .beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .apply(); } ©SoftMoore Consulting
21
Displaying Preferences in an Activity
©SoftMoore Consulting
22
Displaying Preferences in an Activity
©SoftMoore Consulting
23
Relevant Links Storage Options Saving Key-Value Sets Settings
Saving Key-Value Sets Settings SharedPreferences SharedPreferences.Editor ©SoftMoore Consulting
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.