{"id":176,"date":"2014-06-16T07:07:57","date_gmt":"2014-06-16T11:07:57","guid":{"rendered":"https:\/\/cindypotvin.com\/?p=176"},"modified":"2021-08-01T19:57:26","modified_gmt":"2021-08-01T23:57:26","slug":"saving-preferences-in-your-android-application","status":"publish","type":"post","link":"https:\/\/cindypotvin.com\/saving-preferences-in-your-android-application\/","title":{"rendered":"Saving preferences in your Android application"},"content":{"rendered":"

This is the third post in my series about saving data in Android. The other posts can be found here :<\/p>\n\n\n\n

https:\/\/cindypotvin.com\/introduction-how-to-save-data-in-your-android-application\/<\/a>
https:\/\/cindypotvin.com\/saving-data-to-a-file-in-your-android-application\/<\/a><\/p>\n\n\n\n

A preference is a type of data that needs to be saved by most applications. Preferences allow users to change how the application works by giving choices about things like the layout, the features to enable and the measurement units to use to display data. Default preferences should be good enough for most users, but you may need to offer a choice for more advanced users.<\/p>\n\n\n\n

If you must save preferences in your application, the Android SDK includes the Preference<\/em> APIs made specifically to store this kind of data. The preferences are saved by the android.content.SharedPreferences<\/em> class to an XML file that contains pairs of key-value; the values can be booleans, floats, ints, longs or strings. If you application is uninstalled, all the preferences are also removed since the file is saved to the internal storage of the application. The values for the preferences are saved in clear text, so you should encrypt your data if you want to store sensitive information like credentials.<\/p>\n\n\n\n

You can save values directly to the preferences file without user action using the android.content.SharedPreferences<\/em> class, but in general users will set their preferences from a Settings window that can be accessed from the action bar of your application.\u00a0 To create the Settings window, the Preference<\/em> APIs includes a android.preference.PreferenceFragment<\/em> to add to your own activity. This fragment shows a list of preferences and saves the values selected by the user automatically using the android.content.SharedPreferences<\/em> class.<\/p>\n\n\n\n

Before using the android.preference.PreferenceFragment<\/em>, you need to define which preferences will be available from the fragment with a configuration file that is saved to the \/res\/xml\/<\/em> folder. Basic preferences types are available from the Android SDK, but you can also create your own custom preference type by overriding the android.preference.Preference<\/em> class or one of its sub classes. Here is an example of a preferences.xml<\/em> file containing a android.preference.CheckboxPreference<\/em>, a android.preference.ListPreference<\/em> and an android.preference.EditTextPreference :<\/em><\/p>\n\n\n

<PreferenceScreen xmlns:android="http:\/\/schemas.android.com\/apk\/res\/android" >\n<EditTextPreference\n   android:key="welcome_text"\n   android:title="@string\/pref_title_welcome_text"\n   android:summary="@string\/pref_summary_welcome_text"\n   android:defaultValue="@string\/pref_default_welcome_text" \/>\n<ListPreference\n   android:key="welcome_text_color"\n   android:title="@string\/pref_title_welcome_text_color"\n   android:summary="@string\/pref_summary_welcome_text_color"\n   android:defaultValue="@string\/pref_default_welcome_text_color"\n   android:entries="@array\/colorLabelsArray"\n   android:entryValues="@array\/colorValuesArray" \/>\n<CheckBoxPreference\n   android:defaultValue="true"\n   android:key="show_welcome_text"\n   android:title="@string\/pref_title_show_welcome_text"\n   android:summary="@string\/pref_summary_show_welcome_text" \/>\n<\/PreferenceScreen><\/pre>\n\n\n\n

After that, you must use the android.preference.PreferenceFragment<\/em> to create your own fragment and specify the configuration to use. Your own fragment can be extended later on if you need to add custom behaviours by implementing the android.content.SharedPreferences.OnSharedPreferenceChangeListener<\/em> that is triggered when a preference is modified.<\/p>\n\n\n\n

public class SettingsFragment extends PreferenceFragment {\n   @Override\n   public void onCreate(Bundle savedInstanceState) {\n   super.onCreate(savedInstanceState);\n\n   \/\/ Load the preferences as configured in the \/res\/xml\/preferences.xml file\n   \/\/ and displays them.\n   \/\/ The preferences will be automatically saved.\n   addPreferencesFromResource(R.xml.preferences);\n   }\n}\n<\/pre>\n\n\n\n

Finally, to be able to manage your preferences, you must create the activity that hosts the fragment you just defined, which can then be started from another activity by the user.<\/p>\n\n\n\n

public class SettingsActivity extends Activity {\n   @Override\n   protected void onCreate(Bundle savedInstanceState) {\n   super.onCreate(savedInstanceState);\n\n   \/\/ Display the preferences fragment as the content of the activity\n   getFragmentManager().beginTransaction()\n                       .replace(android.R.id.content, new SettingsFragment()).commit();\n   }\n}\n<\/pre>\n\n\n\n

This is enough to save the preferences to a file automatically, but to do something interesting with the preferences saved you must retrieve them in your other activities. To get preferences values, you can use the android.content.SharedPreferences<\/em> class that is returned by the android.preference.PreferenceManager<\/em> for the current context. To complete the previous example, the following code gets the SharedPreferences<\/em> object during the onResume<\/em> event of the activity and modifies the UI according to the current preferences. The onResume <\/em>event is called when the activity starts and when the user comes back from another activity, in that case the SettingsActivity<\/em> we created to manage the preferences.<\/p>\n\n\n\n

public class MainActivity extends Activity {\n   @Override\n   public void onResume() {\n      super.onResume();\n      SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);\n\n      TextView welcomeTextView = (TextView) findViewById(R.id.hello_world_textview);\n\n      String defaultWelcomeText = getResources().getString(R.string.pref_default_welcome_text);\n      String welcomeText = preferences.getString(\"welcome_text\", defaultWelcomeText);\n      welcomeTextView.setText(welcomeText);\n\n      String defaultWelcomeTextColor = getResources()\n                                          .getString(R.string.pref_default_welcome_text_color);\n      String welcomeTextColor = preferences.getString(\"welcome_text_color\",\n                                                      defaultWelcomeTextColor);\n      welcomeTextView.setTextColor(Color.parseColor(welcomeTextColor));\n\n      boolean showWelcomeText = preferences.getBoolean(\"show_welcome_text\", \n                                                       true \/*showWelcomeText*\/);\n      if (showWelcomeText)\n         welcomeTextView.setVisibility(View.VISIBLE);\n      else\n         welcomeTextView.setVisibility(View.INVISIBLE);\n     }\n}\n<\/pre>\n\n\n\n

For the complete example that can be executed, see the following GitHub project : http:\/\/github.com\/CindyPotvin\/androidpreferences<\/a><\/p>\n\n\n

\n <\/div>\n