SharedPreferences共享参数类

一、作用

    主要用于存放软件的配置参数等信息。sharedPreferences用于存取和修改软件配置参数数据的接口,由getSharedPreferences(String, int)函数返回。任何具体的参数,都有一个单独的该类实例向所有客户端共享。修改参数必须通过SharedPreferences.Editor 对象,以确保这些参数在被提交到外存的时候它们的值处于一致的状态和控制之下。该类暂不支持多进程操作,但是以后将提供该功能。

原文:

Interface for accessing and modifying preference data returned by getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage.

Note: currently this class does not support use across multiple processes. This will be added later.

 

二、SharedPreferences.Editor 类简介

public abstract SharedPreferences.Editor edit ()

Create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.

Note that you must call commit() to have any changes you perform in the Editor actually show up in the SharedPreferences.

 

三、存放参数实例源码:

            @Override
public void onClick(View v)
{
String name = nameText.getText().toString();
String age = ageText.getText().toString();
SharedPreferences preferences = getSharedPreferences("itcast",
Context.MODE_WORLD_READABLE);
Editor editor = preferences.edit();
editor.putString("name", name);
editor.putInt("age", new Integer(age));
editor.commit();
Toast.makeText(MainActivity.this, R.string.success, 1).show();
}

四、读取参数实例源码:

            @Override
public void onClick(View v)
{
SharedPreferences preferences = getSharedPreferences("itcast", Context.MODE_PRIVATE);
String name = preferences.getString("name", "");
int age = preferences.getInt("age", 20);
nameText.setText(name);
ageText.setText(String.valueOf(age));
}

五、归纳

通过以上类的介绍和实例源码分析,可以总结出一般步骤:

存放:

1.获得SharedPreferences 的实例对象,通过getSharedPreferences()传递文件名和模式;

2.获得Editor 的实例对象,通过SharedPreferences 的实例对象的edit()方法;

3.存入数据,利用Editor 对象的putXXX()方法;

4.提交修改的数据,利用Editor 对象的commit()方法。

 

读取:

1.获得SharedPreferences 的实例对象,通过getSharedPreferences()传递文件名和模式;

2.读取数据,通过SharedPreferences 的实例对象的getXXX()方法。

 

 

posted @ 2012-01-21 22:23  小文字  阅读(2455)  评论(0编辑  收藏  举报