官方文档介绍:
Using Shared Preferences
TheSharedPreferencesclass provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can useSharedPreferencesto save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
User Preferences
Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, seePreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).
To get aSharedPreferencesobject 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:
- Call
edit()to get aSharedPreferences.Editor. - Add values with methods such as
putBoolean()andputString(). - Commit the new values with
commit()
To read values, useSharedPreferencesmethods such asgetBoolean()andgetString().
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>
/** * @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; }
本文介绍了如何使用SharedPreferences类来保存和检索应用程序中持久的键值对数据,包括如何通过Editor对象写入和读取数据,以及数据的保存形式和读取方式。示例代码展示了如何保存和读取用户的姓名和年龄数据,并解释了数据是如何以XML格式保存的。
2441

被折叠的 条评论
为什么被折叠?



