Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Data Storage: Part 1 (Preferences) 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 Slide 2 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 – int – String • – float – long − Set<String> Shared preference data will persist across user sessions even if the application is killed. ©SoftMoore Consulting Slide 3 Overview of Shared Preferences • Examples of data stored in shared preferences: – user name – email address – password – 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 Slide 4 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 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 Slide 5 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 (deprecated in API level 23) – used if multiple processes are modifying the same SharedPreferences file ©SoftMoore Consulting Slide 6 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 Slide 7 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 Slide 8 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 Slide 9 Differences Between Methods apply() and commit() • 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 Slide 10 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(); • a boolean variable Retrieve shared preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); boolean silentMode = settings.getBoolean("silentMode", false); ©SoftMoore Consulting Slide 11 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 Slide 12 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 Slide 13 Example: Preferences XML File (res/xml/settings.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 ..." android:key="checkboxPref" /> <ListPreference android:title="List Preference" android:summary="This preference allows you to ..." android:key="listPref" android:defaultValue="digiGreen" android:entries="@array/listArray" android:entryValues="@array/listValues" /> </PreferenceCategory> ©SoftMoore Consulting Slide 14 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 Slide 15 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> </PreferenceScreen> ©SoftMoore Consulting Slide 16 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 – call addPreferencesFromResource(R.xml.<filename>) – add the fragment to an Activity just as you would for any other Fragment. See also Android Studio support for creating a Settings Activity. ©SoftMoore Consulting Slide 17 Example 1: Displaying Preferences in an Activity (Prior to Android 3.0) import android.os.Bundle; import android.preference.PreferenceActivity; public class Preferences extends PreferenceActivity { @Override 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 Slide 18 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 { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.settings); } } ©SoftMoore Consulting Slide 19 Example 2: Displaying Preferences in an Activity (continued) import android.app.Activity; import android.os.Bundle; public class SettingsActivity extends Activity { @Override 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 Slide 20 Displaying Preferences in an Activity ©SoftMoore Consulting Slide 21 Displaying Preferences in an Activity ©SoftMoore Consulting Slide 22 Relevant Links • Storage Options https://developer.android.com/guide/topics/data/data-storage.html • Saving Key-Value Sets https://developer.android.com/training/basics/data-storage/shared-preferences.html • Settings https://developer.android.com/guide/topics/ui/settings.html • SharedPreferences https://developer.android.com/reference/android/content/SharedPreferences.html • SharedPreferences.Editor https://developer.android.com/reference/android/content/SharedPreferences.Editor.html ©SoftMoore Consulting Slide 23