Shared Preferences

The shared preferences are managed with the help of getSharedPreferences method of the Context class.

  1. Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.
  2. Many applications may provide a way to capture user preferences for a specific application or activity.
  3. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.
  4. The recommended way is to use by the default mode, without specifying the file name:
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

    MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application.

  6. The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
    SharedPreferences sharedPre=getSharedPreferences("aaa",Activity.MODE_PRIVATE); 在一个应用程序的不同Activity之间共享变量,使用getSharedPreferences(),如果只是想保存一个活动的状态,而不需要和其他活动共享,则可以使用Activity.getPreference()。
  8. getSharedPreferences(name,mode)方法的第一个参数用于指定该文件的名称,名称不用带后缀,后缀会由Android自动加上。getPreferences()只需要一个mode参数,而getSharedPreferences()还需要另外指定名称。

现在我们已经实现通过Preferences 来存取数据了,那么这些数据到底放在了哪里?其实没安装一个应用程序时,在/data/data 目录下都会产生一个文件夹,如果应用程序使用了Preferences, 那么便会在该文件夹下产生一个shared_prefs 文件夹,其中就是我们保存的数据。查看步骤:
1.  启动模拟器,启动Eclipse
2. 在Eclipse中切换到DDMS ,选择File Explorer标签
3. 找到/data/data 目录中用Preferences 来存取的数据存在Activity01.xml文件中。 还是来张图 比较爽



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




Just another site

Jing's Blog

Just another site

Start from here......







Just another site

Where On Earth Is Waldo?

A Project By Melanie Coles

the Serious Computer Vision Blog

A blog about computer vision and serious stuff

Cauthy's Blog

paper review...

Cornell Computer Vision Seminar Blog

Blog for CS 7670 - Special Topics in Computer Vision


Life through nerd-colored glasses

Luciana Haill

Brainwaves Augmenting Consciousness



Dr Paul Tennent

and the university of nottingham

turn off the lights, please

A bunch of random, thinned and stateless thoughts around the Web

%d bloggers like this: