23
Data Storage: Part 1 (Preferences)

Data Storage: Part 1 (Preferences). Data Storage in Android Shared Preferences –lightweight data storage mechanism –primarily for saving application settings

Embed Size (px)

Citation preview

Data Storage: Part 1(Preferences)

©SoftMoore Consulting

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

Slide 2

©SoftMoore Consulting

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.

Slide 3

©SoftMoore Consulting

Overview of Shared Preferences

• Examples of data stored in shared preferences:– user name – password– email 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

Slide 4

©SoftMoore Consulting

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.Slide 5

©SoftMoore Consulting

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

Slide 6

©SoftMoore Consulting

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

Slide 7

©SoftMoore Consulting

Selected Methods forRetrieving 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)

Slide 8

©SoftMoore Consulting

Selected Methods forSaving 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)

Slide 9

©SoftMoore Consulting

Differences Between Methodsapply() 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.

Slide 10

Use apply() if you don't care about the return valueand you’re using this from your application’s UI thread.

©SoftMoore Consulting

Example: Shared Preferences

public static final String PREFS_NAME = "MyPrefsFile";

• Create shared preferencesSharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);SharedPreferences.Editor editor = settings.edit();editor.putBoolean("silentMode", silentMode);

// Commit the edits!editor.apply();

• Retrieve shared preferencesSharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);boolean silentMode = settings.getBoolean("silentMode", false);

Slide 11

a boolean variable

©SoftMoore Consulting

SharedPreferences APIsVersus 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.

Slide 12

©SoftMoore Consulting

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.

Slide 13

©SoftMoore Consulting

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> Slide 14

©SoftMoore Consulting

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">

Slide 15

©SoftMoore Consulting

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>

Slide 16

©SoftMoore Consulting

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.

Slide 17

©SoftMoore Consulting

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); } }

Slide 18

This method is now deprecated.

©SoftMoore Consulting

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); } }

Slide 19

©SoftMoore Consulting

Example 2: Displaying Preferences in an Activity(continued)

import android.app.Activity;import android.os.Bundle;

public class Settings 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(); } }

Slide 20

Displaying Preferences in an Activity

Slide 21©SoftMoore Consulting

Displaying Preferences in an Activity

Slide 22©SoftMoore Consulting

©SoftMoore Consulting

Relevant Links

• Storage Optionshttp://developer.android.com/guide/topics/data/data-storage.html

• Saving Key-Value Setshttp://developer.android.com/training/basics/data-storage/shared-preferences.html

• Settingshttp://developer.android.com/guide/topics/ui/settings.html

• SharedPreferenceshttp://developer.android.com/reference/android/content/SharedPreferences.html

• SharedPreferences.Editorhttp://developer.android.com/reference/android/content/SharedPreferences.Editor.html

Slide 23