现在的位置: 首页 > 综合 > 正文

android 使用sharedPreferences保存用户设置的参数

2017年04月15日 ⁄ 综合 ⁄ 共 2008字 ⁄ 字号 评论关闭

官方文档介绍:

Using Shared Preferences

The SharedPreferences class provides a general framework that allows you to save
and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to
save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).

To get a SharedPreferences object for your application, use one of two methods:

  • getSharedPreferences() - Use this if you need
    multiple preferences files identified by name, which you specify with the first parameter.
  • getPreferences() - Use this if you need only one preferences file for your
    Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

To write values:

  1. Call edit() to get a SharedPreferences.Editor.
  2. Add values with methods such as putBoolean() and putString().
  3. Commit the new values with commit()

To read values, use SharedPreferences methods such as getBoolean() and getString().

a.示例程序:保存用户设置的数据

/**
	 * 保存各项参数
	 * @param name 姓名
	 * @param age 年龄
	 */
	public void save(String name, int age) {
		SharedPreferences preferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
		Editor edit = preferences.edit();
		edit.putString("name", name);
		edit.putInt("age", age);
		edit.commit();
	}

在保存之后,sharedPreferences将会把数据保存在 /data/data/<应用程序包名>/shared_pres/目录下,且使用xml方式保存数据

示例程序保存的数据是:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<int name="age" value="23" />
<string name="name">g形成</string>
</map>

b.示例程序:从sharedPreferences中读取数据

/**
	 * @return 返回参数设置数据
	 */
	public Map<String, String > getPreferences(){
		Map<String, String> params = new HashMap<String, String>();
		SharedPreferences sp = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
		params.put("name", sp.getString("name", ""));
		params.put("age", String.valueOf(sp.getInt("age", 0)));
		return params;
	}

抱歉!评论已关闭.