Archive

Posts Tagged ‘shared preferences’

Shared Preferences

August 25th, 2009 No comments

(Android phone – how-to/example)

The android.content.SharedPreferences may be useful if you want to save some application settings in a file, and share them through-out all the activities in your application. One cool feature is that the SharedPreferences is directly linked to the android.preference package, that is if you use a android.preference.PreferenceActivity in your application for storing/retrieving the setup, all the variables in the setup and the variables in the SharedPreferences will share the same xml file on the disk. This file may be found on disk in /data/data/com.my.package.name/. For more info about creating your own PreferenceActivity consult the appropriate post on this website.

Let’s say you want to store on disk a boolean variable, to know if you want to skip the introduction at the start of the application or not. The code to write the variable is:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor spe = prefs.edit();
spe.putBoolean(KEY_SKIP_INTRO_AT_STARTUP, true); // we just save “true” in the xml file
spe.commit();

The code to read the variable is:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
m_bSkipIntroAtStartup = prefs.getBoolean(KEY_SKIP_INTRO_AT_STARTUP, false); // if it cannot read the value from file, will by default return false

where “this” is the current activity, m_bSkipIntroAtStartup is the variable to be initialized, and KEY_SKIP_INTRO_AT_STARTUP is the string key (ex: String KEY_SKIP_INTRO_AT_STARTUP = “preferences_skip_intro_at_startup”;)

Categories: android java Tags: